Video in progress
When you move from a local HashMap to a distributed map like Hazelcast or Redis, what changes in the semantics, and what do you prepare teams for?
In a distributed map, keys are compared by serialized bytes, not by equals/hashCode, the value you get is a copy, every operation is a network call, and partial failures can happen. If code was written as "it's just a Map", silent bugs appear.
📖 Answer
Many libraries implement the Map interface, and that gives a deceptive convenience. The differences:
-
Key equality. Hazelcast serializes the key and hashes and compares by bytes. If two equal objects (
equalstrue) differ in serialization (for example field order, order inside aHashSet, a field that should have been transient but isn't), they become two different keys. -
The value is a copy.
Cart cart = distributedMap.get(userId);
cart.addItem(item); // only the local copy changed
distributedMap.put(userId, cart); // if you forget this line, the change is lost
On top of that, get + modify + put is not atomic. If two nodes do it at the same time, it is "last write wins". For that you need an EntryProcessor, replace(key, old, new), or Lua/WATCH in Redis.
-
Cost. Every
getmeans network, serialization and deserialization. Agetin a loop becomes an N+1 problem; you need to batch withgetAll. -
Failures. Network drops, timeouts, which node is right during a partition: a local Map had none of these. You need to find out the consistency model (AP or CP) from the documentation.
-
Iteration and
size()may walk the whole cluster, which is very expensive.
What I give teams: a wrapper interface (CartStore) that has only the needed operations, with their semantics written down clearly. I don't pass the Map interface straight into domain code. As keys, only simple types with stable serialization: String, long or a record. And integration tests against a real cluster (Testcontainers), because in embedded mode many problems don't show up.
Sign up to mark studied questions and save your progress.