How to get Synchronized SortedMap in Java ?

In this tutorial, we will learn about How to Get Synchronized SortedMap in Java ?

SortedMap in Java provides an efficient way of storing key/value pairs in sorted order and allows rapid retrieval of the elements in map. SortedMap is a Map that further provides a total ordering on its keys. The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time. This order is reflected when iterating over the sorted map’s collection views (returned by the entrySet, keySet and values methods). Several additional operations are provided to take advantage of the ordering.

The SortedMap extends Map. SortedMap is not synchronized in Java. When we use SortedMap in multithreading environment, it may be possible that each thread is either adding, updating or removing the records/entries which will lead to dirty reads.

To resolve this problem, we can synchronize SortedMap in Java. Snchronization of SortedMap will affect the performance and probably reduce the speed of SortedMap as synchronized method is always slower than non-synchronized one.

Collections class in Java provides synchronizedSortedMap() method to get synchronized SortedMap. We can get synchronized SortedMap using this method.

Syntax of synchronizedSortedMap() method:

Parameters:
map – the SortedMap to be wrapped in a synchronized SortedMap.

Returns:
a synchronized SortedMap.

Example:

Here we will use TreeMap to get SortedMap.

Output:

 

Related posts

Leave a Comment