Search code examples
hazelcast

Multiple Hazelcast instances or one instance


I am new to Hazelcast I could setup the Hazelcast server,start. My web application is a monolothic application and need to introduce a distributed caching mechanism.There will be relatively good amount of hits will be coming so my question is if I write the code something like below will it be a good approach as it will be created many instances. Or is that the behaviour is expected? Sorry for my dump question.

import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.map.IMap;

public class HazlecastMain {
    
    public static void main(String[] args) {        
        
        //Client configuration
        ClientConfig clientConfig = new ClientConfig();
        clientConfig.setClusterName("dev");
        clientConfig.getNetworkConfig().addAddress("http://localhost:8080");    
        
        
        HazelcastInstance newHazelcastInstance = Hazelcast.newHazelcastInstance();
        IMap<Object, Object> map = newHazelcastInstance.getMap("customers");
        map.put("1", "AA");
        map.put("2", "BB");
        map.put("3", "CC");
        
        System.out.println(map.get("1"));
        HazelcastInstance newHazelcastInstance2 = Hazelcast.newHazelcastInstance();
        IMap<Object, Object> map2 = newHazelcastInstance2.getMap("customers");
        
        System.out.println(map2.get("2"));  

    }
}

Solution

  • You don't need to initiate a new instance of Hazelcast each time you want to access a map, same with the getMap invocation, as both these are expensive remote operations. Get a handle to your map with getMap once and continue to use the same reference for all map operations. Also, avoid creating multiple new instances for Hazelcast access and use the one that you had already created - newHazelcastInstance