我需要一些有效的代码来同步两个集合中的项目。我的意思是,当一个项目添加到第一个集合时,它也应该添加到第二个集合,但将项目添加到第二个集合应该异步完成(例如,通过单独的任务,将使用 Spring Boot 调度任务 API 循环调用),以便两个集合包含相同的项目。
假设只有可能添加新项目
这些同步应该是有效的,以便该算法可以在生产环境中工作。 两个列表的同步最多需要几秒钟
你能帮忙吗?
提前致谢
最佳答案
我建议您在读取第二个集合时注意同步的方向(理想情况是在第一个集合的记录期间,但显然这是不可能的)。
Object get(Object key) {
if (compareCollectionsBySize()) //it should be a simple, inexpensive operation
{
return duplicateCollection.get(key);
} else {
//we need synchronization
//it all depends on the duration of the synchronization
//and search costs for the original collection
//in case fast synchronization
synchronizeCollections();
return duplicateCollection.get(key);
}
}
关于Java使用单独的任务异步同步两个集合中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60098610/