thread safe LinkedHashMap without Collections.synchronized

Vik picture Vik · Feb 10, 2016 · Viewed 11.4k times · Source

I am using a LinkedHashMap and the environment is multi threaded so this structure needs to be thread safe. During specific events I need to read the entire map push to db and clear all.

Most of time only writes happen to this map. This map has a limit 50 entries.

I am using Oracle MAF and it does not have Collections.syncronizedMap available. So, what are things I need to put in synchronized blocks to make sure writing and reading doesn't hit me concurrentModificationException etc

Few requirements:

  1. I need to behave it like a circular queue so Overriding removeEldestEntry method of the LinkedHashMap.
  2. I need to preserve the order

Answer

Peter Lawrey picture Peter Lawrey · Feb 10, 2016

So, what are things I need to put in synchronized blocks to make sure writing and reading doesn't hit me concurrentModificationException etc

Everything method call should be in a synchronized block.

The tricky one being the use of an Iterator, as you have to hold the lock for the life of the Iterator. e.g.

// pre Java 5.0 code
synchronized(map) { // the lock has to be held for the whole loop.
    for(Iterator iter = map.entrySet().iterator(); iter.hashNext(); ) {
         Map.Entry entry = iter.next();
         String key = (String) entry.getKey();
         MyType value = (MyType) entry.getValue();
         // do something with key and value.
    }
}