-
Notifications
You must be signed in to change notification settings - Fork 0
/
AtomicVsSynchonise.java
77 lines (72 loc) · 2.24 KB
/
AtomicVsSynchonise.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
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicVsSynchronize {
static final Object LOCK1 = new Object();
static final Object LOCK2 = new Object();
static int i1 = 0;
static int i2 = 0;
static final AtomicInteger ai1 = new AtomicInteger();
static final AtomicInteger ai2 = new AtomicInteger();
public static void main(String... args) throws ExecutionException, InterruptedException {
for (int i = 0; i < 5; i++) {
testSyncInt();
testAtomicInt();
}
}
private static void testSyncInt() throws ExecutionException, InterruptedException {
final int runs = 999999;
ExecutorService es = Executors.newFixedThreadPool(4);
long start = System.nanoTime();
List<Future<Void>> futures = new ArrayList<>();
for (int t = 0; t < 8; t++) {
futures.add(es.submit(new Callable<Void>() {
public Void call() throws Exception {
for (int i = 0; i < runs; i += 2) {
synchronized (LOCK1) {
i1++;
}
synchronized (LOCK2) {
i2++;
}
}
return null;
}
}));
}
for (Future<Void> future : futures) {
future.get();
}
es.shutdown();
long time = System.nanoTime() - start;
System.out.printf("sync + incr: Each increment took an average of %.1f ns%n", (double) time / runs / 2);
}
private static void testAtomicInt() throws ExecutionException, InterruptedException {
final int runs = 999999;
ExecutorService es = Executors.newFixedThreadPool(4);
long start = System.nanoTime();
List<Future<Void>> futures = new ArrayList<>();
for (int t = 0; t < 8; t++) {
futures.add(es.submit(new Callable<Void>() {
public Void call() throws Exception {
for (int i = 0; i < runs; i += 2) {
ai1.incrementAndGet();
ai2.incrementAndGet();
}
return null;
}
}));
}
for (Future<Void> future : futures) {
future.get();
}
es.shutdown();
long time = System.nanoTime() - start;
System.out.printf("incrementAndGet: Each increment took an average of %.1f ns%n", (double) time / runs / 2);
}
}