Searching...
Monday, 23 June 2014

Thread Safe TreeMap (ConcurrentSkipListMap) Example

08:38

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}


0 comments: