user3218475 user3218475 - 1 year ago 118
Java Question

Java map cache for highly multiple threads

Please suggest which map can be used for caching. My use case is a highly multi threaded server that I would like to synchronise put map but get map is not synchronised.

My expectation is: if put happens, then an immediate get should have the latest updated values.

Will ConcuurentHashMap suit? Also I am thinking that HashMap may work as well since put calls are all synchronised.

Also for our use case synchronisation might not be required for entire map during put always which we are doing now, It should be synchronised only if same value tried to be loaded.

To avoid this logic,

if (null == keysMap.get(keyName) && !keysMap.containsKey(keyName)) {
synchronized (keysMap) {
if(!keysMap.containsKey(keyName)) {
keyValue = loadValues(keyName); // Should be synchronised for unique keyName not for all.
keysMap.put(keyName, keyValue);

Please suggest alternate options to avoid all put calls to map synchronisation which we are doing now.

Answer Source

ConcurrentHashMap is the right answer here, as it's safe to use concurrently from multiple threads.

Alternatively, if you can add a library dependency, Guava's Cache might be what you're looking for.

What you must not do is use a HashMap or other thread unsafe structure without proper synchronization on every operation, both reads and mutates. That's simply not thread safe, and can fail in terrible ways.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download