Repository navigation
Expand file tree
/
Copy pathSynchronizedTest.java
More file actions
68 lines (48 loc) · 1.62 KB
/
Copy pathSynchronizedTest.java
File metadata and controls
68 lines (48 loc) · 1.62 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
60
61
62
63
64
65
66
67
68
package com.hellokoding.java.concurrent;
import org.junit.Test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import static com.hellokoding.java.concurrent.ConcurrentUtils.stop;
import static org.assertj.core.api.Assertions.assertThat;
public class SynchronizedTest {
private ExecutorService executorService = Executors.newFixedThreadPool(3);
@Test
public void runAsync() {
Counter counter = new Counter();
for (int i = 0; i < 10000; i++) {
CompletableFuture.runAsync(counter::increaseRunnable);
}
stop(ForkJoinPool.commonPool());
assertThat(counter.count).isEqualTo(10000);
}
@Test
public void runAsyncWithExecutorService() {
Counter counter = new Counter();
for (int i = 0; i < 10000; i++) {
CompletableFuture.runAsync(counter::increaseRunnable, executorService);
}
stop(executorService);
assertThat(counter.count).isEqualTo(10000);
}
@Test
public void supplyAsync() {
Counter counter = new Counter();
for (int i = 0; i < 10000; i++) {
CompletableFuture.supplyAsync(counter::increaseSupplier, executorService);
}
stop(executorService);
assertThat(counter.count).isEqualTo(10000);
}
class Counter {
int count = 0;
synchronized void increaseRunnable() {
count++;
}
synchronized int increaseSupplier() {
count++;
return count;
}
}
}