java linkedhashmap 线程安全,线程安全LinkedHashMap没有Collections.synchronized

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:

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

I need to preserve the order

解决方案

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.

}

}