0

Take an unsynchronised map

Map<Long,Long> map = new HashMap<>();

When we do a map.put(1,2) from one thread, if is possible for some other thread to not see this updated value? I understand how primitives and references can be cached and therefore, synchronisation is needed when they are accessed. But what about the values inside the object itself?

So say one thread does:

map.put(1,2)

And other thread does

map.get(1)

Is it possible for this thread to see null (assuming this thread has the updated reference to the map)? I presume that it should always see the updated value because the object cannot be cached by any thread.

Prashant Pandey
  • 4,332
  • 3
  • 26
  • 44
  • 1
    Yes, it is possible. Actually, it is worse than that: the second thread could see an inconsisten state of the `map`, with broken invariants. – Hulk Nov 03 '20 at 09:07
  • @Hulk what other invariants can be broken? Also, why is this happening? Clearly, only one copy of the object exists on the heap. – Prashant Pandey Nov 03 '20 at 09:08
  • It could be, for example, that the map is in the process of growing its capacity to accomodate for the value to be added when the other thread accesses it. So the state of the map is no longer the one from before the call to `put`, but it is also not yet the state from after the call to `put`. It is somewhere in-between, with some of the internal fields updated and others not. – Hulk Nov 03 '20 at 09:10
  • This is basically the reason for the existence of classes like [ConcurrentHashMap](https://cr.openjdk.java.net/~iris/se/15/latestSpec//api/java.base/java/util/concurrent/ConcurrentHashMap.html), which prevent these kinds of problems. – Hulk Nov 03 '20 at 09:13
  • This related question covers what kind of problems you still have to deal with yourself, even with `ConcurrentHashMap`: https://stackoverflow.com/questions/14947723/is-concurrenthashmap-totally-safe – Hulk Nov 03 '20 at 09:16
  • Regarding `HashMap` and multi-threading, this might be an interesting read: [What implementation detail makes this code fail so easily?](https://stackoverflow.com/q/40927934/2711488) – Holger Nov 25 '20 at 17:55

0 Answers0