I am using Hazelcast for distributed cache (only one instance). In once scenario I am trying to update a value in map.
Based on https://stackoverflow.com/a/33351291/1212903 it seems I have to use EntryProcessor
when doing update operations since its atomic.
EntryProcessor
even if IMap
is distributed?Map.entry.setValue()
to actually update). public class AnalysisResponseProcessor implements EntryProcessor<String, AnalysisResponseMapper> {
@Override
public Object process(Map.Entry<String, AnalysisResponseMapper> entry) {
AnalysisResponseMapper analysisResponseMapper = entry.getValue();
analysisResponseMapper.increaseCount();
entry.setValue(analysisResponseMapper);
return analysisResponseMapper;
}
@Override
public EntryBackupProcessor<String, AnalysisResponseMapper> getBackupProcessor() {
return null;
}
}
How to deal with this scenario?
Answers to your questions:
whether the map is distributed or not, it can be accessed concurrently. If you do a series of get
and put
, someone else can modify the value in the meantime and you will overwrite the update. If you use EntryProcessor
, you can read and update the value in one atomic operation. If only one client updates the map, you can use get
and put
. The entry processor also needs one network round-trip instead of two.
you can return null
for backup processor if you have 0 backups. But if you ever decide to add a backup, then the backup will not be updated. It might be easier to extend AbstractEntryProcessor
where you don't have to deal with the backup processor, it will execute the same logic on main and backup replicas. It's only worth to do the backup processor manually if the computation inside the process
method is heavy.
the return value from the process()
method isn't the updated entry value, but a value that will be returned from map.executeOnKey()
method. If you don't need it, just return null
.