Close

Java Collections - Collections.synchronizedMap() Examples

Java Collections Java Java API 


Class:

java.util.Collections

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

Method:

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)

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


Examples


package com.logicbig.example.collections;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

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

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

final ExecutorService e = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10000; 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 10000
}
}

Output

9943




Using Collections.synchronizedMap

package com.logicbig.example.collections;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

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

public static void main(String... args) throws InterruptedException {
Map<Integer, Integer> m = new HashMap<>();
Map<Integer, Integer> map = Collections.synchronizedMap(m);

final ExecutorService e = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10000; 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 10000

}
}

Output

10000




See Also