I need a map with the following requirements :
It should be highly concurrent. The put()
, get()
and remove()
methods may be called by multiple threads simultaneously.
It should be of fixed size. If the size of the HashMap
reaches to the max value (e.g. 10000), addition of a new entry to the map should not be allowed. It CAN'T be LRU cache where the oldest entry gets removed on reaching maximum size.
ConcurrentHashMap
may satisfy #1. But, not sure how #2 can be implemented on top of ConcurrentHashMap
without impacting concurrency (Adding a custom put()
method which will add to the map only when the size is lesser than the max size, needs to be "synchronized". That will defeat the purpose of using concurrent HashMap
).
Please let me know your thoughts.
You could implement a map that delegates to a ConcurrentHashMap, using a counting semaphore to limit the number of items in the map. The Semaphore class uses an atomically-updated int to keep track of the permits, so it wouldn't incur much extra overhead.