How to Handle Concurrent Access and Modification of a TreeMap Using Concurrent Collections in Java?
Last Updated :
14 Feb, 2024
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.
- Concurrent Collections: Java concurrent collections provide thread-safe alternatives for non-concurrent collections.
- ConcurrentNavigableMap Interface: ConcurrentSkipListMap implements the ConcurrentNavigableMap interface, which offers a concurrently navigable version of a map. It allows for simultaneous access and editing while preserving the elements in order.
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
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
public class ConcurrentTreeMapExample
{
public static void main(String[] args)
{
ConcurrentNavigableMap<Integer, String> concurrentTreeMap = new ConcurrentSkipListMap<>();
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));
}
});
writerThread.start();
readerThread.start();
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:
- We have created a
ConcurrentNavigableMap
instance named concurrentTreeMap
using ConcurrentSkipListMap
, which is a concurrent implementation of NavigableMap
.
- We have created two threads i.e.
writerThread
and readerThread
.
- The
writerThread
inserts key-value pairs into the concurrent TreeMap from 0 to 999.
- The
readerThread
retrieves and prints key-value pairs from the concurrent TreeMap for keys ranging from 0 to 999.
- We have started both the threads using the
start()
method.
- We use the
join()
method to wait for both threads to finish their execution before the program exits.
Share your thoughts in the comments
Please Login to comment...