Fixed Size Parallel Card

I need a card with the following requirements:

  • It must be very parallel. The put() , get() and remove() methods can be called simultaneously by multiple threads.

  • It must have a fixed size. If the HashMap size reaches the maximum value (for example, 10000), adding a new record to the card is not allowed. It CANNOT be an LRU cache, where the oldest entry is deleted when it reaches its maximum size.

ConcurrentHashMap may satisfy # 1. But I'm not sure how No. 2 can be implemented on top of ConcurrentHashMap without affecting concurrency (adding a custom put() method that will add a map only when the size is less than the maximum size should be "synchronized", which will lead to defeat the purpose of using a parallel HashMap ).

Please let me know your thoughts.

+10
java multithreading concurrency java.util.concurrent concurrenthashmap
source share
5 answers

You can implement a map that delegates to ConcurrentHashMap using a counting semaphore to limit the number of elements on the map. The Semaphore class uses an atomically updated int to track permissions, so it will not incur additional additional overhead.

+6
source share

You can do it all yourself, and only one java SE arsenal can provide what you need, but I highly recommend a lighter and more scalable methodology, since all this work alone will reinvent the wheel. Try one of these in memory data networks:

For example, in ehcache, you can achieve what you want with a configuration similar to:

 <cache name="myCache" maxElementsInMemory="10000" eternal="true" overflowToDisk="false" /> 
+2
source share

How about saving the Hashmap size at any time to ensure the total number of elements inserted? You can use AtomicInteger so that you do not have to synchronize / block a regular int and sacrifice the benefits of using ConcurrentHashMap.

+1
source share

If you are using ConcurrentHashMap, which is an obvious choice here, use the concurrencyLevel input for the constructor to increase throughput - this separates the map from multiple zones to avoid puts conflicts.

0
source share

To solve my requirement for a limited parallel hash map: check the size of the map before using it.

0
source share

All Articles