Skip to content

Commit b81681c

Browse files
committed
Test synchronized
1 parent 89a2571 commit b81681c

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.winterbe.java8.samples.concurrent;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.TimeUnit;
5+
6+
/**
7+
* @author Benjamin Winterberg
8+
*/
9+
public class ConcurrentUtils {
10+
11+
public static void stop(ExecutorService executor) {
12+
try {
13+
executor.shutdown();
14+
executor.awaitTermination(5, TimeUnit.SECONDS);
15+
}
16+
catch (InterruptedException e) {
17+
System.err.println("termination interrupted");
18+
}
19+
finally {
20+
if (!executor.isTerminated()) {
21+
System.err.println("killing non-finished tasks");
22+
}
23+
executor.shutdownNow();
24+
}
25+
}
26+
27+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.winterbe.java8.samples.concurrent;
2+
3+
import java.util.concurrent.ExecutorService;
4+
import java.util.concurrent.Executors;
5+
import java.util.stream.IntStream;
6+
7+
/**
8+
* @author Benjamin Winterberg
9+
*/
10+
public class Synchronized1 {
11+
12+
private static final int NUM_INCREMENTS = 10000;
13+
14+
private static int count = 1;
15+
16+
public static void main(String[] args) {
17+
testSyncIncrement();
18+
testNonSyncIncrement();
19+
}
20+
21+
private static void testSyncIncrement() {
22+
count = 1;
23+
24+
ExecutorService executor = Executors.newFixedThreadPool(2);
25+
26+
IntStream.range(0, NUM_INCREMENTS)
27+
.forEach(i -> executor.submit(Synchronized1::incrementSync));
28+
29+
ConcurrentUtils.stop(executor);
30+
31+
System.out.println(" Sync: " + count);
32+
}
33+
34+
private static void testNonSyncIncrement() {
35+
count = 1;
36+
37+
ExecutorService executor = Executors.newFixedThreadPool(2);
38+
39+
IntStream.range(0, NUM_INCREMENTS)
40+
.forEach(i -> executor.submit(Synchronized1::increment));
41+
42+
ConcurrentUtils.stop(executor);
43+
44+
System.out.println("NonSync: " + count);
45+
}
46+
47+
private static synchronized void incrementSync() {
48+
count = count + 1;
49+
}
50+
51+
private static void increment() {
52+
count = count + 1;
53+
}
54+
}

0 commit comments

Comments
 (0)