|
| 1 | +package com.baeldung.concurrent.adder; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import java.util.concurrent.ExecutorService; |
| 6 | +import java.util.concurrent.Executors; |
| 7 | +import java.util.concurrent.TimeUnit; |
| 8 | +import java.util.concurrent.atomic.LongAdder; |
| 9 | +import java.util.stream.IntStream; |
| 10 | + |
| 11 | +import static junit.framework.TestCase.assertEquals; |
| 12 | + |
| 13 | +public class LongAdderTest { |
| 14 | + @Test |
| 15 | + public void givenMultipleThread_whenTheyWriteToSharedLongAdder_thenShouldCalculateSumForThem() throws InterruptedException { |
| 16 | + //given |
| 17 | + LongAdder counter = new LongAdder(); |
| 18 | + ExecutorService executorService = Executors.newFixedThreadPool(8); |
| 19 | + |
| 20 | + int numberOfThreads = 4; |
| 21 | + int numberOfIncrements = 100; |
| 22 | + |
| 23 | + //when |
| 24 | + Runnable incrementAction = () -> IntStream |
| 25 | + .range(0, numberOfIncrements) |
| 26 | + .forEach((i) -> counter.increment()); |
| 27 | + |
| 28 | + for (int i = 0; i < numberOfThreads; i++) { |
| 29 | + executorService.execute(incrementAction); |
| 30 | + } |
| 31 | + |
| 32 | + //then |
| 33 | + executorService.awaitTermination(500, TimeUnit.MILLISECONDS); |
| 34 | + executorService.shutdown(); |
| 35 | + |
| 36 | + assertEquals(counter.sum(), numberOfIncrements * numberOfThreads); |
| 37 | + assertEquals(counter.sum(), numberOfIncrements * numberOfThreads); |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + public void givenMultipleThread_whenTheyWriteToSharedLongAdder_thenShouldCalculateSumForThemAndResetAdderAfterward() throws InterruptedException { |
| 42 | + //given |
| 43 | + LongAdder counter = new LongAdder(); |
| 44 | + ExecutorService executorService = Executors.newFixedThreadPool(8); |
| 45 | + |
| 46 | + int numberOfThreads = 4; |
| 47 | + int numberOfIncrements = 100; |
| 48 | + |
| 49 | + //when |
| 50 | + Runnable incrementAction = () -> IntStream |
| 51 | + .range(0, numberOfIncrements) |
| 52 | + .forEach((i) -> counter.increment()); |
| 53 | + |
| 54 | + for (int i = 0; i < numberOfThreads; i++) { |
| 55 | + executorService.execute(incrementAction); |
| 56 | + } |
| 57 | + |
| 58 | + //then |
| 59 | + executorService.awaitTermination(500, TimeUnit.MILLISECONDS); |
| 60 | + executorService.shutdown(); |
| 61 | + |
| 62 | + assertEquals(counter.sumThenReset(), numberOfIncrements * numberOfThreads); |
| 63 | + assertEquals(counter.sum(), 0); |
| 64 | + } |
| 65 | +} |
0 commit comments