Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent Map with fixed size

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.

like image 715
Arnab Biswas Avatar asked Nov 05 '14 13:11

Arnab Biswas


People also ask

What is difference between synchronizedMap and ConcurrentHashMap?

synchronizedMap() requires each thread to acquire a lock on the entire object for both read/write operations. By comparison, the ConcurrentHashMap allows threads to acquire locks on separate segments of the collection, and make modifications at the same time.

What are the changes in ConcurrentHashMap in Java 8?

Creates a new, empty map with an initial table size based on the given number of elements ( initialCapacity ), table density ( loadFactor ), and number of concurrently updating threads ( concurrencyLevel ).

Is ConcurrentHashMap slower than HashMap?

HashMap, Hashtable, ConcurrentHashMap performance comparison If you notice ConcurrentHashMap is slightly slower performing than HashMap, however it's a 100% thread safe implementation. On the other hand Hashtable is also thread safe implementation, but it's 18 times slower than HashMap for this test scenario.

Is ConcurrentHashMap thread-safe?

ConcurrentHashMap class is thread-safe i.e. multiple threads can operate on a single object without any complications.


1 Answers

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;
    }
}
like image 155
anaken Avatar answered Oct 22 '22 08:10

anaken