A good approach to this problem is to create threads for different copies of the list. However CopyOnWriteArrayList, it is not suitable here, since it creates a copy with each modification, but in your case it would be better to create copies less often.
So, you can implement it manually: the first thread creates a copy of the updated list and publishes it using a variable volatile, the second thread works with this copy (I assume that the first thread changes only the list, not the objects in it):
private volatile List publicList;
List originalList = ...;
while (true) {
modifyList(originalList);
publicList = new ArrayList(originalList);
}
while (true) {
for (Object o: publicList) {
...
}
}
source
share