forked from LuigiCortese/java-certification-ocp8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.java
79 lines (64 loc) · 1.79 KB
/
App.java
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package net.devsedge.concurrentcollections.concurrenthashmap;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import net.devsedge.Util;
/**
*
* @author Luigi Cortese
*
*/
public class App {
static HashMap<String, Integer> hMap;
static ConcurrentHashMap<String, Integer> cMap;
static {
hMap = new HashMap<>();
hMap.put("one", 1);
hMap.put("two", 2);
hMap.put("three", 3);
cMap = new ConcurrentHashMap<>();
cMap.put("one", 1);
cMap.put("two", 2);
cMap.put("three", 3);
}
public static void main(String[] args) throws InterruptedException {
/*
* Trying to iterate&modify the same HashMap Object in two different
* Threads will cause a ConcurrentModificationException on one
* of the two threads
*/
System.out.println("Concurrently modifying HashMap...");
Thread t1=new Thread(new MyRunnable(hMap));
t1.start();
Thread t2=new Thread(new MyRunnable(hMap));
t2.start();
//to avoid mixing the outputs between the examples
t1.join();
t2.join();
/*
* Concurrent modification allowed with ConcurrentHashMap
*/
System.out.println("\nConcurrently modifying ConcurrentHashMap...");
new Thread(new MyRunnable(cMap)).start();
new Thread(new MyRunnable(cMap)).start();
}
}
class MyRunnable implements Runnable {
Map<String, Integer> map;
MyRunnable(Map map) {
this.map = map;
}
@Override
public void run() {
try {
for (String e : map.keySet()) {
map.put("four", 4);
Util.sleep_(1000);
}
System.out.println("...successfully updated!");
} catch (ConcurrentModificationException e) {
System.out.println("...ConcurrentModificationException thrown!");
}
}
}