Given the ConcurrentHashMap javadocs state:
"Iterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator"
I think I am guarranteed that in the example below one or both threads will call fireAllFinished(). Can there ever be a case where neither calls fireAllFinished()?
ConcurrentHashMap<String, Boolean> taskToFinished = new ConcurrentHashMap();
taskToFinished.put("taskA", false);
taskToFinished.put("taskB", false);
public void checkForAllFinished() {
boolean allFinished = true;
for (Boolean taskFinished = tasksToFinished.values()) {
if (!taskFinished) {
allFinished = false;
break;
}
}
if (allFinished) {
fireAllFinished()
}
}
//Thread1
public void run() {
taskToFinished.put("taskA", true);
checkForAllFinished();
}
//Thread1
public void run() {
taskToFinished.put("taskB", true);
checkForAllFinished();
}
(I've omitted some of the thread creation code. I hope the intent is clear)
update: I already saw this more general question: Is iterating ConcurrentHashMap values thread safe?, but wanted to confirm my specific point as
"at some point"
is generally an imprecise concept when dealing with multi-core machines running code out of order, two threads may update different segments of the map 'at the same time', and there is by design no way to lock the entire ConcurrentHashMap.