Concurrent Map with fixed size

Arnab Biswas picture Arnab Biswas · Nov 5, 2014 · Viewed 9.6k times · Source

I need a map with the following requirements :

  1. It should be highly concurrent. The put(), get() and remove() methods may be called by multiple threads simultaneously.

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

Answer

Nathan Hughes picture Nathan Hughes · Nov 5, 2014

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.