Search code examples
hazelcast

HazelCast IMap why EntryProcessor required when updating map values since its a distributed map(single instance scenario)?


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.

  • Why I have to use EntryProcessor even if IMap is distributed?
  • In Entry processor code I don't technically understand the usage of BackupProcessor exactly from the documentation since its distributed.
  • Why the process method returns an Object and it has no effect (we have to set the updated value to 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?


Solution

  • 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.