We run a Hazelcast cluster of 3 machines, each having the same instance of a process. They share amongst others an IMap named waitingMap. In the method activateAnotherBatch() we check for emptiness of the map. If the map is not empty, then we call some method on the map.
I would make this construction normally synchronized if I was developing on one machine. However, synchronizing stuff only works per process/machine, and now we have 3 machines.
Is this safe, or are other machines able to empty the map after the check for being empty and before the call to waitingMap.entrySet().iterator().next(), thus causing an exception?
If so, how can I solve this so that it works safe over N machines?
public Scheduler(HazelcastInstance hci) {
waitingMap = hci.getMap(CMDS_WAITING);
}
private void activateAnotherBatch() {
if (waitingMap.isEmpty())
return;
var batchNr = waitingMap.entrySet().iterator().next().getValue();
waitingMap.forEach((k,v) -> {
if (v.equals(batchNr))
addCmdNr(k, batchNr, Prio.NORMAL);
});
}
private ConcurrentMap<Integer, Integer> waitingMap;