Concurrent Map with fixed size

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.


How about maintaining the size of Hashmap at all times to ensure the total number of elements inserted? You can use AtomicInteger so that you don't have to synchronize/lock a regular int and sacrifice the benefit of using ConcurrentHashMap.


You can do all these yourself, and the java SE arsenal alone might supply what you require, but I strongly recommend an easier and more scalable methodology as doing all this work yourself would be re-inventing the wheel. Try one of these in memory data grids :

  • Ehcache
  • Hazelcast

For instance in ehcache you can achieve what you want by a configuration similar to :

<cache 
 name="myCache"
 maxElementsInMemory="10000"
 eternal="true"
 overflowToDisk="false" />

Try this:

public static class ConcurrentFixedMap<K, V> extends LinkedHashMap<K, V> {
    private final int MAX_ENTRIES;
    private ConcurrentFixedMap(int size) {
        super(size);
        this.MAX_ENTRIES = size;
    }

    public static <K, V> Map<K, V> init(int size) {
        return Collections.synchronizedMap(new ConcurrentFixedMap<>(size));
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > MAX_ENTRIES;
    }
}