I am looking for a solution for the following problem:
I am designing a java class that contain a map, which is being manipulated by multiple threads. Those threads will have operations include:
- iterate : there will be a thread iterating the map, while iterating, it will read and update the values of some entries
- put : one of the thread will add entries to the map
- get : one or more thread will read the map periodically
The challenging part is, I can’t put the mutex on all 3 methods, because iterate will call get and put, which will cause a dead lock.
Please advise how could I design the class and mutex to make it work.
Thanks
The mutex that’s acquired when you use the
synchronizedkeyword are reentrant, so if iterate already owns the mutex, then it can reacquire the same when calling get and put.That said, I’d create your map member field as a
ConcurrentHashMap. Then, youriteratewon’t haveConcurrentModificationExceptionproblems (for more details, see the javadocs of theConcurrentHashMapclass). Similarly locking for bothgetandputwill be handled for you byConcurrentHashMap.