ConcurrentHashMap in Java?

What is the use of ConcurrentHashMap in Java? What are its benefits? How it works? Sample code will also be helpful.

+51
java concurrenthashmap
May 14 '10 at 17:35
source share
6 answers

The point is to provide a HashMap implementation that is thread safe. Several threads can read and write to it without the possibility of receiving outdated or corrupted data. ConcurrentHashMap provides its own synchronization, so you do not need to explicitly synchronize access to it.

Another feature of ConcurrentHashMap is that it provides a putIfAbsent method that will atomically add a mapping if the specified key does not exist. Consider the following code:

 ConcurrentHashMap<String, Integer> myMap = new ConcurrentHashMap<String, Integer>(); // some stuff if (!myMap.contains("key")) { myMap.put("key", 3); } 

This code is not thread safe because another thread may add a mapping for "key" between the contains call and the put call. Correct implementation:

 myMap.putIfAbsent("key", 3); 
+67
May 14 '10 at 17:36
source share

ConcurrentHashMap allow simultaneous access to the map. HashTables also offers synchronized access to the map, but your entire card is locked for any operation.

The logic of ConcurrentHashMap is your entire table is not getting locked , but only part of [ segments ]. Each segment manages its own HashTable. The lock applies only for updates. In case of exemptions, it allows the use of full concurrency.

Let four streams simultaneously work on a card with a capacity of 32, the table is divided into four segments, where each segment controls the hash table of the capacity. The collection contains a list of 16 segments by default, each of which is used to protect (or block) one bucket of cards.

enter image description here

This effectively means that 16 threads can modify the collection at a time. This concurrency level can be increased by using the optional concurrencyLevel constructor argument.

 public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) 

As another answer said, ConcurrentHashMap offers a new putIfAbsent() method that is similar to put, except that the value will not be overridden if the key exists.

 private static Map<String,String> aMap =new ConcurrentHashMap<String,String>(); if(!aMap.contains("key")) aMap.put("key","value"); 

The new method is also faster because it avoids double traversing as described above. contains method must find the segment and iterate over the table to find the key, and again the put method must cross the bucket and place the key.

+27
Sep 27 '13 at 23:35
source share

Indeed, the big functional difference is that it does not throw an exception and / or gets corrupted when someone else changes it while you use it.

With regular collections, if another thread adds or removes an element while accessing it (via an iterator), it throws an exception. ConcurrentHashMap allows them to make changes and not stop the flow.

Keep in mind that it does not provide any synchronization guarantees or promises about the visibility of time changes from one thread to another. (This is similar to read-only data isolation, not a synchronized card, which behaves more like a serializable database isolation (old school row lock-SQL-serializable, not Oracle-ish multiversion serializable :))

The most common use that I know of is caching immutable derived information in App Server environments where many threads can access the same thing and it really doesn't matter if the two can calculate the same value cache and add it twice because they alternate, etc. (for example, it is widely used inside Spring WebMVC to store runtime-dependent configurations, such as mapping URLs to Handler methods.)

+12
May 14 '10 at 17:38
source share

It can be used for memoization:

 import java.util.concurrent.ConcurrentHashMap; public static Function<Integer, Integer> fib = (n) -> { Map<Integer, Integer> cache = new ConcurrentHashMap<>(); if (n == 0 || n == 1) return n; return cache.computeIfAbsent(n, (key) -> HelloWorld.fib.apply(n - 2) + HelloWorld.fib.apply(n - 1)); }; 
+4
Jan 03 '15 at 2:48
source share

1.ConcurrentHashMap is thread safe, code can be accessed by one thread at a time.

2.ConcurrentHashMap synchronizes or blocks a specific part of the Map. To optimize the performance of ConcurrentHashMap, the map is divided into different sections depending on the level of Concurrency. So we do not need to synchronize the entire map object.

Level 3.Default Concurrency is 16, respectively, the card is divided into 16 parts, and each part is controlled by another lock, which can work with 16 threads.

4.ConcurrentHashMap does not allow NULL values. Thus, the key cannot be empty in ConcurrentHashMap.

+1
Sep 08 '17 at 18:30
source share

Hi guys, today we discussed ConcurrentHashMap.
What is ConcurrentHashMap?

ConcurrentHashMap is a class introduced in Java 1.5 that implements ConcurrentMap, as well as the Serializable interface. ConcurrentHashMap improves HashMap when dealing with multiple Theading. As we know, when an application has multithreading, HashMap is not a good choice because there is a performance issue.

There is some key point of ConcurrentHashMap.

  • The underlying data structure for ConcurrentHashMap is HashTable.
  • ConcurrentHashMap is a class. This class is thread safe, which means that multiple threads can access the same thread object without any complexity.
  • The ConcurretnHashMap object is divided by the number of segments according to the level of parallelism.
  • The default concurrency level for ConcurrentHashMap is 16.
  • In ConcurrentHashMap, any number of Thread can perform a search operation, but to update the Thread object, it is necessary to block the segment in which the thread wants to work.
  • This type of locking mechanism is known as segment locking or segment locking.
  • In ConcurrentHashMap, 16 update operations are performed simultaneously.
  • Zero insertion is not possible in ConcurrentHashMap.

Here is the ConcurrentHashMap construct.

  1. ConcurrentHashMap m = new ConcurrentHashMap ();: Creates a new empty card with initial default capacity (16), load factor (0.75) and concurrencyLevel (16).

  2. ConcurrentHashMap m = new ConcurrentHashMap (int initialCapacity);: Creates a new empty card with the specified initial capacity, with a default load factor (0.75) and concurrencyLevel (16).

  3. ConcurrentHashMap m = new ConcurrentHashMap (int initialCapacity, float loadFactor);: Creates a new empty map with the specified initial capacity and load factor and with the default concurrencyLevel parameter (16).

  4. ConcurrentHashMap m = new ConcurrentHashMap (int initialCapacity, float loadFactor, int concurrencyLevel);: creates a new empty map with the specified initial capacity, load factor and level of parallelism.

  5. ConcurrentHashMap m = new ConcurrentHashMap (Map m);: Creates a new map with the same mappings as for this map.

ConcurretHashMap has one method called putIfAbsent (); This method does not allow you to save a duplicate key, see the example below.

  import java.util.concurrent.*; class ConcurrentHashMapDemo { public static void main(String[] args) { ConcurrentHashMap m = new ConcurrentHashMap(); m.put(1, "Hello"); m.put(2, "Vala"); m.put(3, "Sarakar"); // Here we cant add Hello because 1 key // is already present in ConcurrentHashMap object m.putIfAbsent(1, "Hello"); // We can remove entry because 2 key // is associated with For value m.remove(2, "Vala"); // Now we can add Vala m.putIfAbsent(4, "Vala"); System.out.println(m); } } 
0
May 10 '19 at 4:27
source share



All Articles