Hazelcast – Common Pitfalls & Performance Tips
Hazelcast Queue on single machine
Hazelcast queues are stored on a single member (along with a backup on different machines). This effectively means the queue can hold as many items which can be accommodated on a single machine. So, the queue capacity does not scale by adding more members. Loading more data than what a machine can handle in a queue can cause the machine to crash.
Using Map”s set method instead of put
If we use IMap”s put(key, newValue), Hazelcast returns the oldValue. This means, extra computation and time is spent in deserialization. This also includes more data sent from the network. Instead, if we are not interested in the oldValue, we can use set(key, value) which returns void.
Let’s see how to store and inject references to Hazelcast structures. The following code creates a map of the name “stock” and adds Mango at one place and Apple at another.
//initialize hazelcast instance HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance(); // create a map IMap<String, String> hzStockTemp = hazelcast.getMap("stock"); hzStock.put("Mango", "4"); IMap<String, String> hzStockTemp2 = hazelcast.getMap("stock"); hzStock.put("Apple", "3");
However, the problem here is that we are using getMap(“stock”) twice. Although this call seems harmless in a single node environment, it creates slowness in a clustered environment. The function call getMap() involves network round trips to other members of the cluster.
So, it is recommended that we store the reference to the map locally and use the referencing while operating on the map. For example −
// create a map IMap<String, String> hzStock = hazelcast.getMap("stock"); hzStock.put("Mango", "4"); hzStock.put("Apple", "3");
Hazelcast uses serialized data for object comparison
As we have seen in the earlier examples, it is very critical to note that Hazelcast does not use deserialize objects while comparing keys. So, it does not have access to the code written in our equals/hashCode method. According to Hazelcast, keys are equal if the value to all the attributes of two Java objects is the same.
Use monitoring
In a large-scale distributed system, monitoring plays a very important role. Using REST API and JMX for monitoring is very important for taking proactive measures instead of being reactive.
Homogeneous cluster
Hazelcast assumes all the machines are equal, i.e., all the machines have same resources. But if our cluster contains a less powerful machine, for example, less memory, lesser CPU power, etc., then it can create slowness if the computation happens on that machine. Worst, the weaker machine can run out of resources causing cascading failures. So, it is necessary that Hazelcast members have equal resource power.