dsa

Java ConcurrentMap Interface

In this tutorial, we will learn about the Java ConcurrentMap interface and its methods.

The ConcurrentMap interface of the Java collections framework provides a thread-safe map. That is, multiple threads can access the map at once without affecting the consistency of entries in a map.

ConcurrentMap is an interface, which is introduced in JDK 1.5 represents a Map which is capable of handling concurrent access to it and ConcurrentMap interface present in java.util.concurrent package.The ConcurrentMap provides some extra methods apart from what it inherits from the SuperInterface i.e. java.util.Map.

concurrentmap

Example:

/// Java Program to illustrate methods 
// of ConcurrentMap interface 
import java.util.concurrent.*; 
class ConcurrentMapDemo { 
	public static void main(String[] args) 
	{ 
		ConcurrentHashMap m = new ConcurrentHashMap(); 
		m.put(100, "Codemistic"); 
		m.put(101,  "For"); 
		m.put(102, "Coder"); 

		// Here we cant add Hello because 101 key 
		// is already present in ConcurrentHashMap object 
		m.putIfAbsent(101, "Hello"); 

		// We can remove entry because 101 key 
		// is associated with For value 
		m.remove(101, "For"); 

		// Now we can add Hello 
		m.putIfAbsent(101, "Hello"); 

		// We can replace Hello with For 
		m.replace(101, "Hello", "For"); 
		System.out.println(m); 
	} 
} 

} 
output:
{100=Codemistic, 101=For, 102=Coder}

Methods in Java ConcurrentMap Interface

Method Description
Object putIfAbsent(K key, V value) If the specified key is not already associated with a value, associate it with the given value.
boolean remove(Object key, Object value) Removes the entry for a key only if currently mapped to a given value.
boolean replace(K key, V oldValue, V newValue): Replaces the entry for a key only if currently mapped to a given value.