Get Synchronized Map from TreeMap in Java

In this tutorial, we will learn about How to Get Synchronized Map from TreeMap in Java ?

TreeMap in Java provides an efficient way of storing key/value pairs in sorted order and allows rapid retrieval of the elements in map. The TreeMap class extends AbstractMap and implements the NavigableMap interface. TreeMap is not synchronized in Java. When we use TreeMap 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 TreeMap in Java. Snchronization of TreeMap will affect the performance and probably reduce the speed of TreeMap as synchronized method is always slower than non-synchronized one.

Collections class in Java provides synchronizedMap() method to get synchronized Map. We can get synchronized TreeMap using this method.

Syntax of synchronizedMap() method:

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

Returns:
a synchronized map.

Example:

Output:

Related posts

Leave a Comment