Thread Safe TreeMap (ConcurrentSkipListMap) Example

TreeMap is not thread safe and in case two threads are trying to modify the same object it will throw java.util.ConcurrentModificationException.
java.util.concurrent.ConcurrentSkipListMap is the implementation for Thread safe TreeMap and it will keep the natural ordering.

Example

package com.vinod.concurrency;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
public class ConcurrentSkipListMapExample {
	public static void main(String[] args) {
		// Map<String, String> treeMap = new TreeMap<String, String>();
		Map<String, String> treeMap = new ConcurrentSkipListMap<String, String>();
		treeMap.put("1", "sunday");
		treeMap.put("2", "monday");
		treeMap.put("3", "tuesday");
		for (Map.Entry entry : treeMap.entrySet()) {
			System.out.println(entry.getKey());
			treeMap.remove("3");
		}
		System.out.println(treeMap);
	}
}

Output



1
2
{1=sunday, 2=monday}


No comments:

Post a Comment

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts