Simultaneous HashMap: Size Check

Parallel Hashmap can solve the synchronization problem that is visible in hashmap. Thus, adding and removing would be quick if we use key synchronization with hashmap. What about hashmap size checking if mulitple threads checks concurrentHashMap size? we still need the sync keyword: something like the following:

public static synchronized getSize(){ return aConcurrentHashmap.size(); } 
+7
source share
4 answers

concurentHashMap.size() will return the size known at the time of the call, but it may be an obsolete value when you use this number, because another thread added / removed elements in the meantime.

However, the whole purpose of ConcurrentMaps is that you do not need to synchronize it, since it is a thread-safe collection.

+8
source

You can simply call aConcurrentHashmap.size() . However, you should keep in mind that by the time you get the answer, it may already be out of date. This will happen if there is another thread where the map will change at the same time.

+2
source

You do not need to use synchronization with ConcurretnHashMap, except in rare cases when you need to perform several operations atomically.

To just get the size, you can call it without synchronization.


To clarify when I will use synchronization with ConcurrentHashMap ...

Say that you have an expensive property that you want to create upon request. You want to read at the same time, but also want the values ​​to be created only once.

 public ExpensiveObject get(String key) { return map.get(key); // can work concurrently. } public void put(String key, ExepensiveBuilder builder) { // cannot use putIfAbsent because it needs the object before checking. synchronized(map) { if (!map.containsKey(key)) map.put(key, builder.create()); } } 

Note. This requires that all records be synchronized, but reading can still be parallel.

+1
source

ConcurrentHashMap designers have thought about weighting individual operations, such as: get() , put() and remove() on methods that work on a full HashMap, such as isEmpty() or size() . This is because changes to these methods, called (in general), are smaller than other individual methods.

Sync for size() is not needed here. We can get the size by calling concurentHashMap.size() . This method may return obsolete values, since another thread may change the map at the same time. But this is clearly considered violated, as these operations are deprived.

0
source

All Articles