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
If you are using a java version 1.5 or newer you can use
java.util.concurrent.ConcurrentHashMap
.This is the most efficient implementation of a Map to use in a multithread environment.
It adds also some method like
putIfAbsent
very useful for atomic operations on the map.From java doc:
So verify is this is the behaviour you expect from your class.
If your map has only 50 records and needs to be used as a circular Queue why you use a Map? Is not better to use one of the Queue implementations?
If you need to use a LinkedHashMap use the following:
From javadoc of
LinkedHashMap
:https://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html
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.
Most
LinkedHashMap
operations requiresynchronization
in a multi-threaded environment, even the ones that look pure likeget(key)
,get(key)
actually mutates some internal nodes. The easiest you could do is usingCollections.synchronizedMap
.Now if it is not available, you can easily add it, as it is just a simple
decorator
around map thatsynchronize
all operation.