Java ConcurrentHashMap: compute() Example

By Arvind Rai, February 10, 2022
On this page we will learn compute() method of Java ConcurrentHashMap class.
Find the Java doc of compute method.
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) 
1. The compute method computes the value for the specified key. It updates the value with new computed value corresponding to specified key.
2. The compute method invocation is performed atomically.
3. The supplied BiFunction is invoked exactly once per invocation of compute method.

4. Parameters:
key - Key for which the corresponding value is to be computed.
remappingFunction - The BiFunction to compute the value.

5. Returns: The compute method returns the new computed value. It returns null if there is no corresponding value for the specified key.

6. Throws: The compute method can throw following exceptions.
NullPointerException: If specified key or provided remappingFunction is null.
IllegalStateException: If computation is recursive.
RuntimeException: If remappingFunction throws RuntimeException, then compute method will also throw RuntimeException.

Example

ComputeDemo.java
package com.concretepage;
import java.util.concurrent.ConcurrentHashMap;

public class ComputeDemo {
  public static void main(String[] args) {
	System.out.println("--- Example-1 ---");
	ConcurrentHashMap<String, Integer> conMap1 = new ConcurrentHashMap<>();
	conMap1.put("Mahesh", 22);
	conMap1.put("Nilesh", 25);

	Integer v1 = conMap1.compute("Nilesh", (k, v) -> k.length() + v);
	System.out.println("v1: " + v1);
	System.out.println(conMap1);

	System.out.println("--- Example-2 ---");
	ConcurrentHashMap<Integer, String> conMap2 = new ConcurrentHashMap<>();
	conMap2.put(10, "Varanasi");
	conMap2.put(20, "Prayag");

	String v2 = conMap2.compute(10, (k, v) -> v + "-" + k * 2);
	System.out.println("v2: " + v2);
	System.out.println(conMap2);	
  }
} 
Output
--- Example-1 ---
v1: 31
{Mahesh=22, Nilesh=31}
--- Example-2 ---
v2: Varanasi-20
{20=Prayag, 10=Varanasi-20} 

Reference

Java ConcurrentHashMap
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us