|
| 1 | +package com.baeldung.concurrent.atomic; |
| 2 | + |
| 3 | +import static org.junit.Assert.assertEquals; |
| 4 | + |
| 5 | +import java.util.concurrent.ExecutorService; |
| 6 | +import java.util.concurrent.Executors; |
| 7 | +import java.util.concurrent.TimeUnit; |
| 8 | +import java.util.stream.IntStream; |
| 9 | + |
| 10 | +import org.junit.Ignore; |
| 11 | +import org.junit.Test; |
| 12 | + |
| 13 | +public class CounterTest { |
| 14 | + |
| 15 | + /** |
| 16 | + * This test shows the behaviour of a thread-unsafe class in a multithreaded scenario. We are calling |
| 17 | + * the increment methods 1000 times from a pool of 3 threads. In most of the cases, the counter will |
| 18 | + * less than 1000, because of lost updates, however, occasionally it may reach 1000, when no threads |
| 19 | + * called the method simultaneously. This may cause the build to fail occasionally. Hence excluding this |
| 20 | + * test by adding Ignore annotation. |
| 21 | + */ |
| 22 | + @Test |
| 23 | + @Ignore |
| 24 | + public void givenMultiThread_whenUnsafeCounterIncrement() throws InterruptedException { |
| 25 | + ExecutorService service = Executors.newFixedThreadPool(3); |
| 26 | + UnsafeCounter unsafeCounter = new UnsafeCounter(); |
| 27 | + |
| 28 | + IntStream.range(0, 1000) |
| 29 | + .forEach(count -> service.submit(unsafeCounter::increment)); |
| 30 | + service.awaitTermination(100, TimeUnit.MILLISECONDS); |
| 31 | + |
| 32 | + assertEquals(1000, unsafeCounter.getValue()); |
| 33 | + } |
| 34 | + |
| 35 | + @Test |
| 36 | + public void givenMultiThread_whenSafeCounterWithLockIncrement() throws InterruptedException { |
| 37 | + ExecutorService service = Executors.newFixedThreadPool(3); |
| 38 | + SafeCounterWithLock safeCounter = new SafeCounterWithLock(); |
| 39 | + |
| 40 | + IntStream.range(0, 1000) |
| 41 | + .forEach(count -> service.submit(safeCounter::increment)); |
| 42 | + service.awaitTermination(100, TimeUnit.MILLISECONDS); |
| 43 | + |
| 44 | + assertEquals(1000, safeCounter.getValue()); |
| 45 | + } |
| 46 | + |
| 47 | + @Test |
| 48 | + public void givenMultiThread_whenSafeCounterWithoutLockIncrement() throws InterruptedException { |
| 49 | + ExecutorService service = Executors.newFixedThreadPool(3); |
| 50 | + SafeCounterWithoutLock safeCounter = new SafeCounterWithoutLock(); |
| 51 | + |
| 52 | + IntStream.range(0, 1000) |
| 53 | + .forEach(count -> service.submit(safeCounter::increment)); |
| 54 | + service.awaitTermination(100, TimeUnit.MILLISECONDS); |
| 55 | + |
| 56 | + assertEquals(1000, safeCounter.getValue()); |
| 57 | + } |
| 58 | +} |
0 commit comments