1

I have a scenario When multiple threads are writing to one LinkedHashMap, on iterating through Map after execution is completed only one key value pair is retained added by last thread.

Please advice me on this.

Thanks

ankita shukla
  • 47
  • 1
  • 7
  • what else do you expect from an unsafe/not synchronized `LinkedHashMap`? Take a look at [this question](https://stackoverflow.com/questions/35321481/thread-safe-linkedhashmap-without-collections-synchronized) – Andrew Tobilko Jun 20 '18 at 20:11

1 Answers1

0

Note that the LinkedHashMap implementation is not synchronized. If multiple threads access a linked hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. This is typically accomplished by synchronizing on some object. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

Map m = Collections.synchronizedMap(new LinkedHashMap(...));
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63