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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

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

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Java Concurrency: Understanding the ‘Volatile’ Keyword
  • DataWeave Interview Question: Concatenate Elements of an Array
  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems
  • Selenium Grid Tutorial: Essential Tips and How to Set It Up

Trending

  • Unlocking AI Coding Assistants Part 2: Generating Code
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • Doris: Unifying SQL Dialects for a Seamless Data Query Ecosystem
  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  1. DZone
  2. Data Engineering
  3. Data
  4. ConcurrentHashMap: Call Only One Method Per Key

ConcurrentHashMap: Call Only One Method Per Key

Using the ConcurrentHashMap in a thread-safe way is easy.

By 
Thomas Krieger user avatar
Thomas Krieger
·
Updated Mar. 16, 20 · Tutorial
Likes (17)
Comment
Save
Tweet
Share
24.5K Views

Join the DZone community and get the full member experience.

Join For Free

Each method of ConcurrentHashMap is thread-safe. But calling multiple methods from ConcurrentHashMap for the same key leads to race conditions. And calling the same method from ConcurrentHashMap recursively for different keys leads to deadlocks.

 

Let us look at an example to see why this happens:

 

Calling Multiple Methods

 

In the following test, I use two methods from ConcurrentHashMap for the same key 1. The method  update, line 3 till 10, first gets the value from the  ConcurrentHashMap  using the method  get. Than update increments the value and put it back using the method  put , line 6 and 8:

 

    Java   
         
   
           
     
       
     
     
       
     
     
     
     
     
     
     
     
            x         
            33           
          
           
         
          
           
         
          
                       
          
             1            
            
import com.vmlens.api.AllInterleavings;
           
             2            
            
public class TestUpdateWrong {
           
             3            
            
    public void update(ConcurrentHashMap<Integer, Integer> map) {
           
             4            
            
        Integer result = map.get(1);
           
             5            
            
        if (result == null) {
           
             6            
            
            map.put(1, 1);
           
             7            
            
        } else {
           
             8            
            
            map.put(1, result + 1);
           
             9            
            
        }
           
             10            
            
    }
           
             11            
            
    @Test
           
             12            
            
    public void testUpdate() throws InterruptedException {
           
             13            
            
        try (AllInterleavings allInterleavings = 
           
             14            
            
            new AllInterleavings("TestUpdateWrong");) {
           
             15            
            
            while (allInterleavings.hasNext()) {
           
             16            
            
                final ConcurrentHashMap<Integer, Integer> map = 
           
             17            
            
                        new ConcurrentHashMap<Integer, Integer>();
           
             18            
            
                Thread first = new Thread(() -> {
           
             19            
            
                    update(map);
           
             20            
            
                });
           
             21            
            
                Thread second = new Thread(() -> {
           
             22            
            
                    update(map);
           
             23            
            
                });
           
             24            
            
                first.start();
           
             25            
            
                second.start();
           
             26            
            
                first.join();
           
             27            
            
                second.join();
           
             28            
            
                assertEquals(2, map.get(1).intValue());
           
             29            
            
            }
           
             30            
            
        }
           
             31            
            
    }
           
             32            
            
}
      
       
     
      
       
       

 

To test what happens  I use two threads, created in line 18 and 21. I start those two threads, in line 25 and 25. And then wait till both are ended using thread join,in line 26 and 27. After both threads are stopped I check if the value is indeed two,line 28.

 

To test all thread interleavings we put the complete test in a while loop iterating over all thread interleavings using the class  AllInterleavings from vmlens, line 15. Running the test I see the following error:

 

java.lang.AssertionError: expected:<2> but was:<1>

 


 

To see why the result is one, not two as expected we can look at the report vmlens generated:

 

Image title

 

So. the problem is that first both threads call get, and after that, both threads call put. So, both threads see an empty value and update the value to one. This leads to a result of one and not, as expected, two. The trick to solving this race condition is to use only one method instead of two methods to update the value. Using the method compute, we can do this. So, the correct version looks like this:

 

public void update() {
    map.compute(1, (key, value) -> {
        if (value == null) {
            return 1;
        } else {
            return value + 1;
        }
    });
}

 


 

Calling the Same Method Recursively

 

Now, let us look at an example for calling the same method from ConcurrentHashMap recursively:

 

public class TestUpdateRecursive {
    private final ConcurrentHashMap<Integer, Integer> map = 
            new ConcurrentHashMap<Integer, Integer>();
    public TestUpdateRecursive() {
        map.put(1, 1);
        map.put(2, 2);
    }
    public void update12() {
        map.compute(1,  (key,value) ->   {   
               map.compute(2, ( k , v ) ->  {  return 2; }  );   
               return 2;       
        });
    }   
    public void update21() {
        map.compute(2,  (key,value) ->   {   
               map.compute(1, ( k , v ) ->  {  return 2; }  );   
               return 2;       
        });
    }
    @Test
    public void testUpdate() throws InterruptedException    {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute( () -> { update12();   }  );    
        executor.execute( () -> { update21();   }  );
        executor.shutdown();
        executor.awaitTermination(10, TimeUnit.MINUTES);
    }   

}

 


 

Here, we call the compute method inside of the compute method for different keys. Once for the key, one then two, and once for the key, two then one. If we run the test, we see the following deadlock:

 

Image title

 

To understand why this deadlock happens, we have to look at the internals of the ConcurrentHashMap. ConcurrentHashMap uses an array to store the mapping between the keys and the values. Every time we update such a mapping of the ConcurrentHashMap, it locks the array element in which the mapping is stored. So in our test, the call to compute for the key one locked the array element for the key one. And then, we try to lock the array element for the key two. But this key is already locked by the other thread who called compute for key two and tries to lock the array element for the key one. A deadlock.

 

Note that only updates need a lock to an array element. Methods that are read-only, like, for example,get, do not use locks. So, it is no problem to use a get method inside a compute call.

 

Conclusion

 

Using the ConcurrentHashMap in a thread-safe way is easy. Select one method that best fits your needs — and use it exactly once per key

Testing Data structure Lock (computer science) Element Threading Race condition Interleaving (disk storage) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Java Concurrency: Understanding the ‘Volatile’ Keyword
  • DataWeave Interview Question: Concatenate Elements of an Array
  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems
  • Selenium Grid Tutorial: Essential Tips and How to Set It Up

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!