|
| 1 | +package com.baeldung.concurrent.synchronize; |
| 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 BaeldungSynchronizeMethodsTest { |
| 14 | + |
| 15 | + @Test |
| 16 | + @Ignore |
| 17 | + public void givenMultiThread_whenNonSyncMethod() throws InterruptedException { |
| 18 | + ExecutorService service = Executors.newFixedThreadPool(3); |
| 19 | + BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods(); |
| 20 | + |
| 21 | + IntStream.range(0, 1000) |
| 22 | + .forEach(count -> service.submit(method::calculate)); |
| 23 | + service.awaitTermination(100, TimeUnit.MILLISECONDS); |
| 24 | + |
| 25 | + assertEquals(1000, method.getSum()); |
| 26 | + } |
| 27 | + |
| 28 | + @Test |
| 29 | + public void givenMultiThread_whenMethodSync() throws InterruptedException { |
| 30 | + ExecutorService service = Executors.newFixedThreadPool(3); |
| 31 | + BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods(); |
| 32 | + |
| 33 | + IntStream.range(0, 1000) |
| 34 | + .forEach(count -> service.submit(method::synchronisedCalculate)); |
| 35 | + service.awaitTermination(100, TimeUnit.MILLISECONDS); |
| 36 | + |
| 37 | + assertEquals(1000, method.getSyncSum()); |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + public void givenMultiThread_whenStaticSyncMethod() throws InterruptedException { |
| 42 | + ExecutorService service = Executors.newCachedThreadPool(); |
| 43 | + |
| 44 | + IntStream.range(0, 1000) |
| 45 | + .forEach(count -> service.submit(BaeldungSynchronizedMethods::syncStaticCalculate)); |
| 46 | + service.awaitTermination(100, TimeUnit.MILLISECONDS); |
| 47 | + |
| 48 | + assertEquals(1000, BaeldungSynchronizedMethods.staticSum); |
| 49 | + } |
| 50 | + |
| 51 | +} |
0 commit comments