|
| 1 | +package com.hellokoding.java.concurrent; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import java.util.concurrent.CompletableFuture; |
| 6 | +import java.util.concurrent.ExecutorService; |
| 7 | +import java.util.concurrent.Executors; |
| 8 | +import java.util.concurrent.ForkJoinPool; |
| 9 | + |
| 10 | +import static com.hellokoding.java.concurrent.ConcurrentUtils.stop; |
| 11 | +import static org.assertj.core.api.Assertions.assertThat; |
| 12 | + |
| 13 | +public class SynchronizedTest { |
| 14 | + private ExecutorService executorService = Executors.newFixedThreadPool(3); |
| 15 | + |
| 16 | + @Test |
| 17 | + public void runAsync() { |
| 18 | + Counter counter = new Counter(); |
| 19 | + |
| 20 | + for (int i = 0; i < 10000; i++) { |
| 21 | + CompletableFuture.runAsync(counter::increaseRunnable); |
| 22 | + } |
| 23 | + |
| 24 | + stop(ForkJoinPool.commonPool()); |
| 25 | + |
| 26 | + assertThat(counter.count).isEqualTo(10000); |
| 27 | + } |
| 28 | + |
| 29 | + @Test |
| 30 | + public void runAsyncWithExecutorService() { |
| 31 | + Counter counter = new Counter(); |
| 32 | + |
| 33 | + for (int i = 0; i < 10000; i++) { |
| 34 | + CompletableFuture.runAsync(counter::increaseRunnable, executorService); |
| 35 | + } |
| 36 | + |
| 37 | + stop(executorService); |
| 38 | + |
| 39 | + assertThat(counter.count).isEqualTo(10000); |
| 40 | + } |
| 41 | + |
| 42 | + @Test |
| 43 | + public void supplyAsync() { |
| 44 | + Counter counter = new Counter(); |
| 45 | + |
| 46 | + for (int i = 0; i < 10000; i++) { |
| 47 | + CompletableFuture.supplyAsync(counter::increaseSupplier, executorService); |
| 48 | + } |
| 49 | + |
| 50 | + stop(executorService); |
| 51 | + |
| 52 | + assertThat(counter.count).isEqualTo(10000); |
| 53 | + } |
| 54 | + |
| 55 | + class Counter { |
| 56 | + int count = 0; |
| 57 | + |
| 58 | + synchronized void increaseRunnable() { |
| 59 | + count++; |
| 60 | + } |
| 61 | + |
| 62 | + synchronized int increaseSupplier() { |
| 63 | + count++; |
| 64 | + |
| 65 | + return count; |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments