DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Merge HTML Documents in Java
  • The Future of Java and AI: Coding in 2025
  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Using Python Libraries in Java

Trending

  • How to Perform Custom Error Handling With ANTLR
  • Data Quality: A Novel Perspective for 2025
  • Agile’s Quarter-Century Crisis
  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  1. DZone
  2. Coding
  3. Java
  4. ConcurrentHashMap in Java 8

ConcurrentHashMap in Java 8

This overview of ConcurrentHashMap covers its use in parallel programming and the various methods you can implement to make use of it.

By 
Arun Pandey user avatar
Arun Pandey
DZone Core CORE ·
Mar. 09, 17 · Tutorial
Likes (40)
Comment
Save
Tweet
Share
87.3K Views

Join the DZone community and get the full member experience.

Join For Free

ConcurrentHashMap has been a very popular data structure these days. In this talk, we will walk through the new features that got introduced in Java 8.

Java 8 introduced the forEach, search, and reduce methods, which are pretty much to support parallelism. These three operations are available in four forms: accepting functions with keys, values, entries, and key-value pair arguments.

All of those methods take a first argument called parallelismThreshold.

We will take the example of this map definition:

ConcurrentHashMap<String, Integer> hashMap = new ConcurrentHashMap<>();
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);
hashMap.put("D", 4);
hashMap.put("E", 5);
hashMap.put("F", 6);
hashMap.put("G", 7);


parallelismThreshold

This is to define how you wanted to execute the operations — sequentially or in parallel. Suppose you have given a parallelismThreshold as 2. So as long as there are fewer than two elements in your map, it would be sequential. Otherwise, it's parallel (depends on the JVM).

hashMap.forEach(2, (k, v) -> System.out.println("key->" + k + "is related with value-> " + v +", by thread-> "+ Thread.currentThread().getName())); 


It produced the below o/p on my machine (you can see two different threads in action — main and ForkJoinPool.commonPool-worker-1):

key->A is related with value-> 1, by thread-> main
key->D is related with value-> 4, by thread-> ForkJoinPool.commonPool-worker-1
key->B is related with value-> 2, by thread-> main
key->E is related with value-> 5, by thread-> ForkJoinPool.commonPool-worker-1
key->C is related with value-> 3, by thread-> main
key->F is related with value-> 6, by thread-> ForkJoinPool.commonPool-worker-1
key->G is related with value-> 7, by thread-> ForkJoinPool.commonPool-worker-1


forEach

This method has the signature:

public void forEach(long parallelismThreshold, BiConsumer action)

We have already seen the parallelismThreshold. Now, let's dive into BiConsumer. It's a FunctionalInterface that accepts two input arguments and returns no result. It has this definition:

@FunctionalInterface
public interface BiConsumer<T, U> {
  void accept(T t, U u);
}


So forEach takes parallelismThreshold and BiConsumer and calls this method:

new ForEachMappingTask (null, batchFor(parallelismThreshold), 0, 0, table, action).invoke();


The batchFor(parallelismThreshold) method is to get parallelism using the ForkJoinPool.getCommonPoolParallelism() method, as we have seen above in the parallelismThreshold example.

Here, action is the BiConsumer that we passed in forEach method.

ForEachMappingTask is a static final class that extends BulkTask, and BulkTask extends the abstract class CountedCompleter, which extends the abstract class ForkJoinTask. So in short, ForEachMappingTask is to support ForkJoinTask.

The ForEachMappingTask class has the method compute as below:

public final void compute() {
final BiConsumer<? super K, ? super V> action;
    if ((action = this.action) != null) {
      for (int i = baseIndex, f, h; batch > 0 &&
      (h = ((f = baseLimit) + i) >>> 1) > i;) {
        addToPendingCount(1);
        new ForEachMappingTask<K,V> (this, batch >>>= 1, 
            baseLimit = h, f, tab, action).fork();
      }
      for (Node<K,V> p; (p = advance()) != null; )
      action.accept(p.key, p.val);
 propagateCompletion();
    }
}


Each time we execute a sub-task, the addToPendingCount(int) method gets invoked as in the above code. This is just to have a counter, which is to determine if task execution is completed.

The compute method above is responsible for adding the sub-task to a queue (shared/unshared queue) using the fork method of ForkJoinTask, as seen in the above code.

new ForEachMappingTask (this, batch >>>= 1, baseLimit = h, f, tab, action).fork();

Let's understand the BiConsumer's accept method with the example below:

import java.util.function.BiConsumer;
public class BiConsumerTest {
  public static void main(String[] args) {
    BiConsumer<String, String> biConsumer = (x, y) -> {
      System.out.println("Key => " + x + ", and value => "+ y);
    };
    biConsumer.accept("k", "arun");
  }
}


Other ForkJoinTasks, such as RecursiveTask and RecursiveAction, don't need any explicit call to finish their job, while in the case of CountedCompleter, an explicit call of propagateCompletion() is required.

It's the same thing you've seen in the compute method.

As we have seen above, calling the invoke method of ForEachMappingTask, since ForEachMappingTask extends ForkJoinTask; implementation as below -

public final V invoke() {
  int s;
  if ((s = doInvoke() & DONE_MASK) != NORMAL)
    reportException(s);
  return getRawResult();
}


Here, getRawResult() returns the result of the computation, which is null by default. Otherwise, it should be overridden.

Search

Let's see a search snippet:

String result = hashMap.search(1, (k, v) -> {
  System.out.println(Thread.currentThread().getName());
  if (k.equals("A"))
    return k +"-" +v;
  return null;
});
System.out.println("result => " +result);


O/P:

main
ForkJoinPool.commonPool-worker-2
ForkJoinPool.commonPool-worker-2
result => A-1


The method signature of the search method is:

public U search(long parallelismThreshold, BiFunction searchFunction)

The search method calls the invoke method of SearchMappingsTask. SearchMappingsTask is a subclass of BulkTask, which we have seen already. SearchmappingTask has a compute method as below:

public final void compute() {
  final BiFunction<? super K, ? super V, ? extends U> searchFunction;
  final AtomicReference<U> result;
  if ((searchFunction = this.searchFunction) != null &&
   (result = this.result) != null) {
  for (int i = baseIndex, f, h; batch > 0 &&
 (h = ((f = baseLimit) + i) >>> 1) > i;) {
      if (result.get() != null)
        return;
      addToPendingCount(1);
      new SearchMappingsTask<K,V,U>(this, batch >>>= 1, 
        baseLimit = h, f, tab, searchFunction, result).fork();
}
while (result.get() == null) {
      U u;
      Node<K,V> p;
      if ((p = advance()) == null) {
        propagateCompletion();
        break;
      }
      if ((u = searchFunction.apply(p.key, p.val)) != null) {
        if (result.compareAndSet(null, u))
          quietlyCompleteRoot();
        break;
      }
    }
  }
}


In above method, AtomicReference is used to have an object reference, which may be updated atomically, since it's a result. Each time a sub-task is executed, the addToPendingCount(int) method is getting invoked as in the above code. This is just to have a counter to determine if task execution is going well. And after that, it's calling the fork method to make it parallel.

Other ForkJoinTasks, such as RecursiveTask and RecursiveAction, don't need any explicit call to finish their job, while in the case of CountedCompleter, an explicit call of propagateCompletion() is required. Later, the quietlyCompleteRoot() method is completes the task normally.

Merge

As per the Javadoc, "If the specified key is not already associated with a (non-null) value, associates it with the given value. Otherwise, replaces the value with the results of the given remapping function, or removes if null. The entire method invocation is performed atomically. Some attempted update operations on this map by other threads may be blocked while computation is in progress, so the computation should be short and simple, and must not attempt to update any other mappings of this Map."

Let us look at the code snippet for the same:

ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
map.put("X", "x");
System.out.println("1st ==> " +map);
System.out.println("2nd ==> " + map.merge("X", "x", (v1, v2) -> null));
System.out.println("3rd ==> " +map);
map.put("Y", "y");
map.put("X", "x1");
System.out.println("4th ==> " +map.merge("X", "x1", (v1, v2) -> "z"));
System.out.println("5th ==> " +map);
System.out.println("6th ==> " +map.merge(
 "X", "x1", (v1, v2) -> v2.concat("z")));
System.out.println("7th ==> " +map);


O/P:

1st ==> {X=x}
2nd ==> null
3rd ==> {}
4th ==> z
5th ==> {X=z, Y=y}
6th ==> x1z
7th ==> {X=x1z, Y=y}


The method signature of the merge method is:

public V merge(K key, V value, BiFunction remappingFunction)


Here, remappingFunction is the function that recomputes a value if present.

getOrDefault

As per the Javadoc, "It returns the value to which the specified key is mapped, or the given default value if this map contains no mapping for the key."

Let us look at the code snippet:

ConcurrentHashMap<String, Integer> defaultMap = 
  new ConcurrentHashMap<String, Integer>();
defaultMap.put("X", 30);
System.out.println(defaultMap);
System.out.println(defaultMap.getOrDefault("Y", 21));


O/P:

{X=30}
21


Compute

Generally, we do some computation on map values and store it back. In the concurrent model, it's difficult to manage, and that's the reason Java introduced the compute method. The entire method invocation is performed atomically.

The compute and computeIfPresent methods take a remapping function as an argument to compute a value, and remapping is of type BiFunction. The computeIfAbsent method takes an argument as mappingFunction to compute a value, and hence mappingFunction is of type Function.

Let us look at the code snippet to understand this:

ConcurrentHashMap<String, Integer> map1 = new ConcurrentHashMap<>();
map1.put("A", 1);
map1.put("B", 2);
map1.put("C", 3);
// Compute a new value for the existing key
System.out.println("1st print => " +map1.compute("A",
  (k, v) -> v == null ? 42 : v + 40));
System.out.println("2nd print => " + map1);
// This will add a new (key, value) pair
System.out.println("3rd print => " + map1.compute("X",
  (k, v) -> v == null ? 42 : v + 41));
System.out.println("4th print => " + map1);

//computeIfPresent method
System.out.println("5th print => " + map1.computeIfPresent("X", (k, v) -> v == null ? 42 : v + 10));
System.out.println("6th print => " + map1);

//computeIfAbsent method
System.out.println("7th print => " + map1.computeIfAbsent("Y", (k) -> 90));
System.out.println("8th print => " + map1);


O/P:

1st print => 41
2nd print => {A=41, B=2, C=3}
3rd print => 42
4th print => {A=41, B=2, C=3, X=42}
5th print => 52
6th print => {A=41, B=2, C=3, X=52}
7th print => 90
8th print => {A=41, B=2, C=3, X=52, Y=90}


Reduce 

The reduce method signature is:

public U reduce(long parallelismThreshold, BiFunction transformer, BiFunction reducer)


Here, transformer is a function returning the transformation for an element, or null if there is no transformation (in which case it is not combined), and reducer is a commutative associative combining function.

The reduce method calls the MapReduceMappingsTask's invoke method. MapReduceMappingsTask extends BulkTask, and we have seen this already.

Let us look at the example below:

ConcurrentHashMap<String, Integer> reducedMap = new ConcurrentHashMap<>();
reducedMap.put("One", 1);
reducedMap.put("Two", 2);
reducedMap.put("Three", 3);
System.out.println("reduce example => " 
 +reducedMap.reduce(2, (k, v) -> v*2, (total, elem) -> total + elem)); 

System.out.println("reduceKeys example => " 
 +reducedMap.reduceKeys(2, (key1, key2) -> key1.length() > key2.length() ? key1 + "-"+key2 : key2 + "-"+key1)); 

System.out.println("reduceValues example => " 
 +reducedMap.reduceValues(2, (v) -> v*2 , (value1, value2) -> value1 > value2 ? value1 - value2 : value2 - value1));
System.out.println("After reduce => " +reducedMap);


O/P:

reduce example => 12
reduceKeys example => Three-Two-One
reduceValues example => 0
After reduce => {One=1, Two=2, Three=3}


Have a great day learning. Enjoy!

Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • How to Merge HTML Documents in Java
  • The Future of Java and AI: Coding in 2025
  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Using Python Libraries in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!