Repository navigation
Expand file tree
/
Copy pathSynchronizeHashMap.java
More file actions
48 lines (38 loc) · 1.49 KB
/
Copy pathSynchronizeHashMap.java
File metadata and controls
48 lines (38 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package corejava.collections;
import java.util.Collections;
import java.util.Date;
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;
/**
*
* 1. synchronizedMap can make Map object Synchronized - all method will be synchronized
* Thread Safety , Negative Performance , data consistent in MultiThreaded Environment
*
* 2. HashMap - High Performance , Not Thread safe - data might inconsistent in Multithread env( how ?)
*
* **/
public class SynchronizeHashMap {
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); // all object and its method got synchronized
//Map<Integer, Integer> map = new HashMap<>();
Date date = new Date();
long start = date.getTime();
final ExecutorService e = Executors.newFixedThreadPool(10);
for (int i = 0; i < 50000; i++) {
e.execute(() -> {map.put(counter.incrementAndGet(), (int) (Math.random() * 100));
System.out.println(Thread.currentThread());
});
}
e.shutdown();
e.awaitTermination(1000, TimeUnit.SECONDS);
Date date2= new Date();
long end = date2.getTime();
System.out.println(map.size() +" HashMap vs synchronizedMap Time Diff:" + (end - start));// should be 10000
}
}