-
Notifications
You must be signed in to change notification settings - Fork 343
Expand file tree
/
Copy pathSynchronizationOnMutableFieldDemo.java
More file actions
59 lines (50 loc) 路 1.9 KB
/
Copy pathSynchronizationOnMutableFieldDemo.java
File metadata and controls
59 lines (50 loc) 路 1.9 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
49
50
51
52
53
54
55
56
57
58
59
package fucking.concurrency.demo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @author Jerry Lee (oldratlee at gmail dot com)
*/
public class SynchronizationOnMutableFieldDemo {
private static final int ADD_COUNT = 10_000;
private static volatile List<Listener> listeners = new CopyOnWriteArrayList<>();
public static void main(String[] args) throws Exception {
Thread thread1 = new Thread(new ConcurrencyCheckTask());
thread1.start();
Thread thread2 = new Thread(new ConcurrencyCheckTask());
thread2.start();
thread1.join();
thread2.join();
int actualSize = listeners.size();
int expectedSize = ADD_COUNT * 2;
if (actualSize != expectedSize) {
// On my dev machine, it almost always occurs!
// Simple and safe solution:
// make the List field final and use a thread-safe List, such as CopyOnWriteArrayList
System.err.printf("Fuck! Lost update on mutable field! actual %,d, expected %,d.%n", actualSize, expectedSize);
} else {
System.out.println("Emm... Got the right size!");
}
}
@SuppressWarnings("SynchronizeOnNonFinalField")
private static void addListener(Listener listener) {
synchronized (listeners) {
List<Listener> results = new ArrayList<>(listeners);
results.add(listener);
listeners = results;
}
}
private static class ConcurrencyCheckTask implements Runnable {
@Override
public void run() {
System.out.println("ConcurrencyCheckTask started!");
for (int i = 0; i < ADD_COUNT; ++i) {
addListener(new Listener());
}
System.out.println("ConcurrencyCheckTask stopped!");
}
}
private static class Listener {
// stub class
}
}