concurrent HashMap: checking size

concurrenthashmap putifabsent
concurrenthashmap computeifabsent
when to use concurrenthashmap
concurrenthashmap thread-safe
concurrenthashmap remove
concurrenthashmap iterator
concurrenthashmap interview questions
concurrenthashmap size performance

Concurrent Hashmap could solve synchronization issue which is seen in hashmap. So adding and removing would be fast if we are using synchronize key work with hashmap. What about checking hashmap size, if mulitple threads checking concurrentHashMap size? do we still need synchronzation key word: something as follows:

public static synchronized getSize(){
     return aConcurrentHashmap.size();
}  

concurentHashMap.size() will return the size known at the moment of the call, but it might be a stale value when you use that number because another thread has added / removed items in the meantime.

However the whole purpose of ConcurrentMaps is that you don't need to synchronize it as it is a thread safe collection.

ConcurrentHashMap size() Method in Java, ConcurrentHashMap.size() method is an in-built function in Java which ConcurrentHashMap<Integer, String> Check out this Author's contributed articles. Default concurrency-level of ConcurrentHashMap is 16. In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updation in object, thread must lock the particular segment in which thread want to operate.This type of locking mechanism is known as Segment locking or bucket locking .Hence at a time 16 updation

You can simply call aConcurrentHashmap.size(). However, you have to bear in mind that by the time you get the answer it might already be obsolete. This would happen if another thread where to concurrently modify the map.

ConcurrentHashMap (Java Platform SE 8 ), Bear in mind that the results of aggregate status methods including size Legacy method testing if some key maps into the specified value in this table. boolean  Note that usage of size() of ConcurrentHashMap should be replaced by mappingCount(), for the latter method returns a long count, although deep down they are based on the same estimation. hashCode matters : note that using many keys with exactly the same hashCode() is a sure way to slow down a performance of any hash table.

You don't need to use synchronized with ConcurretnHashMap except in very rare occasions where you need to perform multiple operations atomically.

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


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

Say you have an expensive object you want to create on demand. You want concurrent reads, but also want to ensure that values are only created 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 writes are synchronized, but reads can still be concurrent.

ConcurrentHashMap (Java Platform SE 7 ), Legacy method testing if some key maps into the specified value in this table. boolean int, size(). Returns the number of key-value mappings in this map. The extra objects created per concurrent hashmap using default constructor are normally in ratio of 1 to 50 i.e. for 100 such instance of ConcurrentHashMap, there will be 5000 extra objects created. Based on above, I will suggest to use the constructor parameters wisely to reduce the number of unnecessary objects and improving the performance .

The designers of ConcurrentHashMap thought of giving weightage to individual operations like : get(), put() and remove() over methods which operate over complete HashMap like isEmpty() or size(). This is done because the changes of these methods getting called (in general) are less than the other individual methods.

A synchronization for size() is not needed here. We can get the size by calling concurentHashMap.size() method. This method may return stale values as other thread might modify the map in the meanwhile. But, this is explicitely assumed to be broken as these operations are deprioritized.

java.util.concurrent.ConcurrentHashMap.size java code examples , ConcurrentHashMap.size (Showing top 20 results out of 6,570) toFormatter(); if (cPatternCache.size() < PATTERN_CACHE_SIZE) { // the size check is not  Refactor design and do not use size method with concurrent access. To use methods as size and isEmpty you can use synchronized collection Collections.synchronizedMap. Synchronized collections achieve their thread safety by serializing all access to the collection's state. The cost of this approach is poor concurrency; when multiple threads

ConcorrentHashMap is fail-safe. it won't give any concurrent modification exceptions. it works good for multi threaded operations. The whole implementation of ConcurrentHashMap is same as HashMap but the while retrieving the elements , HashMap locks whole map restricting doing further modifications which gives concurrent modification exception.' But in ConcurrentHashMap, the locking happens at bucket level so the chance of giving concurrent modification exception is not present.

So to answer you question here, checking size of ConcurrentHashMap doesn't help because , it keeps chaining based on the operations or modification code that you write on the map. It has size method which is same from the HashMap.

A Guide to ConcurrentMap, CHECK OUT THE COURSE ConcurrentHashMap is the out-of-box ready ConcurrentMap implementation. constructors are only present for backward compatibility: the parameters can only affect the initial size of the map. Returns the number of mappings. This method should be used instead of size() because a ConcurrentHashMap may contain more mappings than can be represented as an int. The value returned is an estimate; the actual count may differ if there are concurrent insertions or removals.

Curious case of ConcurrentHashMap - Romil Jain, c) After identifying the bucket, iterate over the linked-list to check the key By default ConcurrentHashMap has segment array size as 16 so  The concurrent map, as opposed to non concurrent hashmap, does not fast-fail if you add stuff while iterating on it. However, there is no guarantee about when and if the iterator (or the get() method, or any other read operation) will see newly added/removed elements or not.

ConcurrentHashMap.java, All list additions are at the front of each bin, making it easy to check changes, and also fast to public ConcurrentHashMap(Map t) { this(Math.max((int) (t.size()  HashMap is the Class which is under Traditional Collection and ConcurrentHashMap is a Class which is under Concurrent Collections, apart from this there are various differences between them which are: HashMap is non-Synchronized in nature i.e. HashMap is not Thread-safe whereas ConcurrentHashMap is Thread-safe in nature.

Top 25 Examples of ConcurrentHashMap in Java 8, Once you add an entry, the size of the map is increased by 1, and you can 20) How to check if a key exists in ConcurrentHashmap - containsKey() example. Segment array size = 2 to the power x, where result should be ≥ concurrencyLevel (in our case it is 10) Segment array size = 2 ^ 4 = 16 ≥ 10 which means Segment array size should be 16.

Comments
  • ConcurrentHashMap is synchronized internally. Adding your own synchronize blocks over the top may not give you what you want.
  • @krock You have to be careful how you use it. Adding an example.