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.
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.
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 ).
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.
ConcurrentHashMap class is thread-safe i.e. multiple threads can operate on a single object without any complications.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With