javaserializationequalshazelcastin-memory-data-grid

Hazelcast object equals for replace method callingfrom client


I have configured hazelcast map with in-memory-format: OBJECT. Now I am trying to use method map.replace(key,oldValue,newVal) assuming that it will use defined equals method in my class. But I make call not in hazelcast instance, but from separate client, aka from another jvm. I tried to copy the same class to hazelcast application, but it doesn't work, it continue to compare by binary.


Solution

  • You will see that it works. Start your member with user code deployment

    public static void main(String[] args) {
      Config config = new Config();
      UserCodeDeploymentConfig userCodeDeploymentConfig = 
      config.getUserCodeDeploymentConfig();
      userCodeDeploymentConfig.setEnabled(true);
            
      MapConfig mapConfig = config.getMapConfig("mymap");
      mapConfig.setInMemoryFormat(InMemoryFormat.OBJECT);
      HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(config);
    }
    

    On the client side have a class as below

    package com.colak.datastructures.map;
    
    public class Worker implements Serializable {
    
      String name;
    
      public Worker(String name) {
        this.name = name;
      }
    
      @Override
      public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Worker worker = (Worker) o;
        return Objects.equals(name, worker.name);
      }
    
      @Override
      public int hashCode() {
        return Objects.hash(name);
      }
    }
    

    Then start your client and deploy your domain object to member

    public static void main(String[] args) {
      ClientConfig clientConfig = new ClientConfig();
    
      ClientUserCodeDeploymentConfig userCodeDeploymentConfig = 
        clientConfig.getUserCodeDeploymentConfig();
      userCodeDeploymentConfig.setEnabled(true);
      userCodeDeploymentConfig.addClass(com.colak.datastructures.map.Worker.class);
    
      HazelcastInstance hazelcastInstance = HazelcastClient.newHazelcastClient(clientConfig);
    
      IMap<Integer, Worker> map = hazelcastInstance.getMap("mymap");
      Worker worker1 = new Worker("john");
      Worker worker2 = new Worker("jane");
    
      int key = 1;
      map.put(key, worker1);
      Worker receivedWorker = map.get(key);
    
      if (!receivedWorker.equals(worker1)) {
        throw new IllegalStateException("receivedWorker is not equal to worker1");
      }
    
      map.replace(key, worker1, worker2); // Here replace workers for the same key
      receivedWorker = map.get(key);
      if (!receivedWorker.equals(worker2)) {
        throw new IllegalStateException("receivedWorker is not equal to worker2");
      }
    }
    

    You can see that worker1 is replaced with worker2 for key = 1