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

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts