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.
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.
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.