Close

Java Collections - Collections.synchronizedSortedMap() Examples

Java Collections Java Java API 


Class:

java.util.Collections

java.lang.Objectjava.lang.Objectjava.util.Collectionsjava.util.CollectionsLogicBig

Method:

public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)

Returns a synchronized (thread-safe) SortedMap backed by the specified SortedMap.


Examples


package com.logicbig.example.collections;

import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class SynchronizedSortedMapExample {

private static AtomicInteger counter = new AtomicInteger();

public static void main(String... args) throws InterruptedException {
SortedMap<Integer, Integer> map = new TreeMap<>();

final ExecutorService e = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
e.execute(() -> map.put(counter.incrementAndGet(),
(int) (Math.random() * 100)));
}
e.shutdown();
e.awaitTermination(1000, TimeUnit.SECONDS);
System.out.println(map.size());//should be 10
}

}

Output

8




using synchronizedSortedMap

package com.logicbig.example.collections;

import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class SynchronizedSortedMapExample2 {
private static AtomicInteger counter = new AtomicInteger();

public static void main(String... args) throws InterruptedException {

SortedMap<Integer, Integer> m = new TreeMap<>();
SortedMap<Integer, Integer> map = Collections.synchronizedSortedMap(m);

final ExecutorService e = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
e.execute(() -> map.put(counter.incrementAndGet(),
(int) (Math.random() * 100)));
}
e.shutdown();
e.awaitTermination(1000, TimeUnit.SECONDS);
System.out.println(map.size());//should be 10
}
}

Output

10




See Also