Open In App

How to Handle Concurrent Access and Modification of a TreeMap Using Concurrent Collections in Java?

To solve data corruption in a multithreaded context, and thread safety, Java offers concurrent collections in the java.util.concurrent package.

In this article, we will learn the use of concurrent collections to manage simultaneous access and change of a TreeMap.



Program to Manage Concurrent Access and Modification of a TreeMap in Java

Let’s use ConcurrentSkipListMap to see how to manage concurrent access and modification of a TreeMap.




// Java Program to Handle Concurrent Access
// And Modification of a TreeMap using Concurrent Collections 
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
  
// Driver Class
public class ConcurrentTreeMapExample 
{
      // Main Function
    public static void main(String[] args) 
    {
        // Creating a concurrent TreeMap
        ConcurrentNavigableMap<Integer, String> concurrentTreeMap = new ConcurrentSkipListMap<>();
  
        // Creating threads to perform concurrent operations
        Thread writerThread = new Thread(() -> 
           {
            for (int i = 0; i < 1000; i++) 
            {
                concurrentTreeMap.put(i, "" + i);
            }
        });
  
        Thread readerThread = new Thread(() -> 
           {
            for (int i = 0; i < 1000; i++) {
                System.out.println("Key: " + i + ", Value: " + concurrentTreeMap.get(i));
            }
        });
  
        // Start threads
        writerThread.start();
        readerThread.start();
  
        // Wait for threads to finish
        try 
        {
            writerThread.join();
            readerThread.join();
        
        catch (InterruptedException e) 
        {
            e.printStackTrace();
        }
    }
}

Output

Key: 0, Value: null
Key: 1, Value: 1
Key: 2, Value: 2
Key: 3, Value: 3
Key: 4, Value: 4
Key: 5, Value: 5
Key: 6, Value: 6
Key: 7, Value: 7
Key: 8, Value: 8
Key: 9, Value: 9
Key: 10, Value: 10
Key: 11,...

Explanation of the above Program:


Article Tags :