From 515e4caaca07032e213b0afe09d90d8cda3bd13f Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Sun, 27 Aug 2017 13:39:19 +0200 Subject: [PATCH] Add core-java-concurrency to main pom (#2507) * Add core-java-concurrency * Refactor codebase --- .../atomic/SafeCounterWithLock.java | 4 ++-- .../atomic/SafeCounterWithoutLock.java | 4 ++-- .../concurrent/atomic/UnsafeCounter.java | 6 ++--- .../com/baeldung/threadlocal/Context.java | 6 ++--- .../threadlocal/SharedMapWithUserContext.java | 4 ++-- .../ThreadLocalWithUserContext.java | 2 +- .../baeldung/threadlocal/UserRepository.java | 2 +- .../com/baeldung/threadpool/CountingTask.java | 8 ++++--- .../com/baeldung/threadpool/TreeNode.java | 17 +++++++++----- .../com/baeldung/transferqueue/Consumer.java | 6 ++--- .../com/baeldung/transferqueue/Producer.java | 6 ++--- .../CompletableFutureLongRunningUnitTest.java | 6 ++++- .../CountdownLatchExampleIntegrationTest.java | 10 +++++---- .../SquareCalculatorIntegrationTest.java | 1 - ...nchronizedHashMapWithRWLockManualTest.java | 4 +--- .../ConcurrentMapNullKeyValueManualTest.java | 2 +- .../ConcurrentNavigableMapManualTest.java | 22 +++++++++---------- .../ConcurrentModificationUnitTest.java | 15 ++++++------- .../Java8ExecutorServiceIntegrationTest.java | 2 +- ...adPoolInParallelStreamIntegrationTest.java | 5 ++++- pom.xml | 1 + 21 files changed, 74 insertions(+), 59 deletions(-) diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java index 38633011bfd7..e3a1629ce109 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java @@ -3,11 +3,11 @@ public class SafeCounterWithLock { private volatile int counter; - public int getValue() { + int getValue() { return counter; } - public synchronized void increment() { + synchronized void increment() { counter++; } } diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java index 41e10789a6e4..18ade35efbf8 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java @@ -5,11 +5,11 @@ public class SafeCounterWithoutLock { private final AtomicInteger counter = new AtomicInteger(0); - public int getValue() { + int getValue() { return counter.get(); } - public void increment() { + void increment() { while(true) { int existingValue = getValue(); int newValue = existingValue + 1; diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java index 8a7278884262..500ef5bd7e70 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java +++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/atomic/UnsafeCounter.java @@ -1,13 +1,13 @@ package com.baeldung.concurrent.atomic; public class UnsafeCounter { - int counter; + private int counter; - public int getValue() { + int getValue() { return counter; } - public void increment() { + void increment() { counter++; } } diff --git a/core-java-concurrency/src/main/java/com/baeldung/threadlocal/Context.java b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/Context.java index 241fb2f1e023..88b78fb259d6 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/threadlocal/Context.java +++ b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/Context.java @@ -4,14 +4,14 @@ public class Context { private final String userName; - public Context(String userName) { + Context(String userName) { this.userName = userName; } @Override public String toString() { return "Context{" + - "userNameSecret='" + userName + '\'' + - '}'; + "userNameSecret='" + userName + '\'' + + '}'; } } diff --git a/core-java-concurrency/src/main/java/com/baeldung/threadlocal/SharedMapWithUserContext.java b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/SharedMapWithUserContext.java index e5854e218a27..8cb4b3968f2c 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/threadlocal/SharedMapWithUserContext.java +++ b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/SharedMapWithUserContext.java @@ -5,11 +5,11 @@ import java.util.concurrent.ConcurrentHashMap; public class SharedMapWithUserContext implements Runnable { - public final static Map userContextPerUserId = new ConcurrentHashMap<>(); + final static Map userContextPerUserId = new ConcurrentHashMap<>(); private final Integer userId; private UserRepository userRepository = new UserRepository(); - public SharedMapWithUserContext(Integer userId) { + SharedMapWithUserContext(Integer userId) { this.userId = userId; } diff --git a/core-java-concurrency/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java index de7e4a0369c8..d4ab906c308f 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java +++ b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/ThreadLocalWithUserContext.java @@ -10,7 +10,7 @@ public class ThreadLocalWithUserContext implements Runnable { private final Integer userId; private UserRepository userRepository = new UserRepository(); - public ThreadLocalWithUserContext(Integer userId) { + ThreadLocalWithUserContext(Integer userId) { this.userId = userId; } diff --git a/core-java-concurrency/src/main/java/com/baeldung/threadlocal/UserRepository.java b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/UserRepository.java index 3fe76f75c070..2597594940b1 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/threadlocal/UserRepository.java +++ b/core-java-concurrency/src/main/java/com/baeldung/threadlocal/UserRepository.java @@ -4,7 +4,7 @@ public class UserRepository { - public String getUserNameForUserId(Integer userId) { + String getUserNameForUserId(Integer userId) { return UUID.randomUUID().toString(); } } diff --git a/core-java-concurrency/src/main/java/com/baeldung/threadpool/CountingTask.java b/core-java-concurrency/src/main/java/com/baeldung/threadpool/CountingTask.java index effdf5491671..a7447d040fda 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/threadpool/CountingTask.java +++ b/core-java-concurrency/src/main/java/com/baeldung/threadpool/CountingTask.java @@ -2,19 +2,21 @@ import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveTask; -import java.util.stream.Collectors; public class CountingTask extends RecursiveTask { private final TreeNode node; - public CountingTask(TreeNode node) { + CountingTask(TreeNode node) { this.node = node; } @Override protected Integer compute() { - return node.value + node.children.stream().map(childNode -> new CountingTask(childNode).fork()).collect(Collectors.summingInt(ForkJoinTask::join)); + return node.getValue() + node.getChildren().stream() + .map(childNode -> new CountingTask(childNode).fork()) + .mapToInt(ForkJoinTask::join) + .sum(); } } diff --git a/core-java-concurrency/src/main/java/com/baeldung/threadpool/TreeNode.java b/core-java-concurrency/src/main/java/com/baeldung/threadpool/TreeNode.java index 9b431520746d..65dfed01a29f 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/threadpool/TreeNode.java +++ b/core-java-concurrency/src/main/java/com/baeldung/threadpool/TreeNode.java @@ -1,18 +1,25 @@ package com.baeldung.threadpool; -import java.util.Set; - import com.google.common.collect.Sets; +import java.util.Set; + public class TreeNode { - int value; + private int value; - Set children; + private Set children; - public TreeNode(int value, TreeNode... children) { + TreeNode(int value, TreeNode... children) { this.value = value; this.children = Sets.newHashSet(children); } + public int getValue() { + return value; + } + + public Set getChildren() { + return children; + } } diff --git a/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Consumer.java b/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Consumer.java index a5f70d9df54e..f3be6a030ec5 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Consumer.java +++ b/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Consumer.java @@ -11,10 +11,10 @@ public class Consumer implements Runnable { private final TransferQueue transferQueue; private final String name; - private final int numberOfMessagesToConsume; - public final AtomicInteger numberOfConsumedMessages = new AtomicInteger(); + final int numberOfMessagesToConsume; + final AtomicInteger numberOfConsumedMessages = new AtomicInteger(); - public Consumer(TransferQueue transferQueue, String name, int numberOfMessagesToConsume) { + Consumer(TransferQueue transferQueue, String name, int numberOfMessagesToConsume) { this.transferQueue = transferQueue; this.name = name; this.numberOfMessagesToConsume = numberOfMessagesToConsume; diff --git a/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Producer.java b/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Producer.java index c7df7c410a3d..b73cf5ac1907 100644 --- a/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Producer.java +++ b/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Producer.java @@ -12,10 +12,10 @@ public class Producer implements Runnable { private final TransferQueue transferQueue; private final String name; - private final Integer numberOfMessagesToProduce; - public final AtomicInteger numberOfProducedMessages = new AtomicInteger(); + final Integer numberOfMessagesToProduce; + final AtomicInteger numberOfProducedMessages = new AtomicInteger(); - public Producer(TransferQueue transferQueue, String name, Integer numberOfMessagesToProduce) { + Producer(TransferQueue transferQueue, String name, Integer numberOfMessagesToProduce) { this.transferQueue = transferQueue; this.name = name; this.numberOfMessagesToProduce = numberOfMessagesToProduce; diff --git a/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java index 0a6d94e12644..45d2ec68e4ec 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/completablefuture/CompletableFutureLongRunningUnitTest.java @@ -4,7 +4,11 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.*; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.stream.Collectors; import java.util.stream.Stream; diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java index fc343e4cee93..d49a8b8590c2 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchExampleIntegrationTest.java @@ -18,7 +18,9 @@ public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion() thro // Given List outputScraper = Collections.synchronizedList(new ArrayList<>()); CountDownLatch countDownLatch = new CountDownLatch(5); - List workers = Stream.generate(() -> new Thread(new Worker(outputScraper, countDownLatch))).limit(5).collect(toList()); + List workers = Stream.generate(() -> new Thread(new Worker(outputScraper, countDownLatch))) + .limit(5) + .collect(toList()); // When workers.forEach(Thread::start); @@ -26,7 +28,6 @@ public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion() thro outputScraper.add("Latch released"); // Then - outputScraper.forEach(Object::toString); assertThat(outputScraper).containsExactly("Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Latch released"); } @@ -35,7 +36,9 @@ public void whenFailingToParallelProcess_thenMainThreadShouldTimeout() throws In // Given List outputScraper = Collections.synchronizedList(new ArrayList<>()); CountDownLatch countDownLatch = new CountDownLatch(5); - List workers = Stream.generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch))).limit(5).collect(toList()); + List workers = Stream.generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch))) + .limit(5) + .collect(toList()); // When workers.forEach(Thread::start); @@ -63,7 +66,6 @@ public void whenDoingLotsOfThreadsInParallel_thenStartThemAtTheSameTime() throws outputScraper.add("Workers complete"); // Then - outputScraper.forEach(Object::toString); assertThat(outputScraper).containsExactly("Workers ready", "Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Workers complete"); } diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java index 5f8b05a974a4..c2513f38c18c 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/future/SquareCalculatorIntegrationTest.java @@ -22,7 +22,6 @@ public class SquareCalculatorIntegrationTest { private static final Logger LOG = LoggerFactory.getLogger(SquareCalculatorIntegrationTest.class); - @Rule public TestName name = new TestName(); diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java index 3014ae38b27f..f3ced219f71e 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/locks/SynchronizedHashMapWithRWLockManualTest.java @@ -49,9 +49,7 @@ private void executeWriterThreads(SynchronizedHashMapWithRWLock object, int thre private void executeReaderThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) { for (int i = 0; i < threadCount; i++) - service.execute(() -> { - object.get("key" + threadCount); - }); + service.execute(() -> object.get("key" + threadCount)); } } diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java index 33e332642762..cbac6e7f4c53 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java @@ -12,7 +12,7 @@ public class ConcurrentMapNullKeyValueManualTest { - ConcurrentMap concurrentMap; + private ConcurrentMap concurrentMap; @Before public void setup() { diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java index 768c31ee8009..c0753db5135f 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java @@ -18,7 +18,7 @@ public class ConcurrentNavigableMapManualTest { public void givenSkipListMap_whenAccessInMultiThreads_thenOrderingStable() throws InterruptedException { NavigableMap skipListMap = new ConcurrentSkipListMap<>(); - updateMapConcurrently(skipListMap, 4); + updateMapConcurrently(skipListMap); Iterator skipListIter = skipListMap.keySet().iterator(); int previous = skipListIter.next(); @@ -28,9 +28,9 @@ public void givenSkipListMap_whenAccessInMultiThreads_thenOrderingStable() throw } } - private void updateMapConcurrently(NavigableMap navigableMap, int concurrencyLevel) throws InterruptedException { - ExecutorService executorService = Executors.newFixedThreadPool(concurrencyLevel); - for (int i = 0; i < concurrencyLevel; i++) { + private void updateMapConcurrently(NavigableMap navigableMap) throws InterruptedException { + ExecutorService executorService = Executors.newFixedThreadPool(4); + for (int i = 0; i < 4; i++) { executorService.execute(() -> { ThreadLocalRandom random = ThreadLocalRandom.current(); for (int j = 0; j < 10000; j++) { @@ -45,26 +45,26 @@ private void updateMapConcurrently(NavigableMap navigableMap, i @Test public void givenSkipListMap_whenNavConcurrently_thenCountCorrect() throws InterruptedException { NavigableMap skipListMap = new ConcurrentSkipListMap<>(); - int count = countMapElementByPollingFirstEntry(skipListMap, 10000, 4); + int count = countMapElementByPollingFirstEntry(skipListMap); assertEquals(10000 * 4, count); } @Test public void givenTreeMap_whenNavConcurrently_thenCountError() throws InterruptedException { NavigableMap treeMap = new TreeMap<>(); - int count = countMapElementByPollingFirstEntry(treeMap, 10000, 4); + int count = countMapElementByPollingFirstEntry(treeMap); assertNotEquals(10000 * 4, count); } - private int countMapElementByPollingFirstEntry(NavigableMap navigableMap, int elementCount, int concurrencyLevel) throws InterruptedException { - for (int i = 0; i < elementCount * concurrencyLevel; i++) { + private int countMapElementByPollingFirstEntry(NavigableMap navigableMap) throws InterruptedException { + for (int i = 0; i < 10000 * 4; i++) { navigableMap.put(i, i); } AtomicInteger counter = new AtomicInteger(0); - ExecutorService executorService = Executors.newFixedThreadPool(concurrencyLevel); - for (int j = 0; j < concurrencyLevel; j++) { + ExecutorService executorService = Executors.newFixedThreadPool(4); + for (int j = 0; j < 4; j++) { executorService.execute(() -> { - for (int i = 0; i < elementCount; i++) { + for (int i = 0; i < 10000; i++) { if (navigableMap.pollFirstEntry() != null) { counter.incrementAndGet(); } diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java index f7a7bd5fe054..9cdac72d59cf 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java @@ -2,7 +2,6 @@ import org.junit.Test; -import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; @@ -28,9 +27,9 @@ public void givenIterating_whenUsingIteratorRemove_thenNoError() throws Interrup List integers = newArrayList(1, 2, 3); - for (Iterator iterator = integers.iterator(); iterator.hasNext();) { + for (Iterator iterator = integers.iterator(); iterator.hasNext(); ) { Integer integer = iterator.next(); - if(integer == 2) { + if (integer == 2) { iterator.remove(); } } @@ -45,7 +44,7 @@ public void givenIterating_whenUsingRemovalList_thenNoError() throws Interrupted List toRemove = newArrayList(); for (Integer integer : integers) { - if(integer == 2) { + if (integer == 2) { toRemove.add(integer); } } @@ -69,10 +68,10 @@ public void whenUsingStream_thenRemoveElements() { Collection integers = newArrayList(1, 2, 3); List collected = integers - .stream() - .filter(i -> i != 2) - .map(Object::toString) - .collect(toList()); + .stream() + .filter(i -> i != 2) + .map(Object::toString) + .collect(toList()); assertThat(collected).containsExactly("1", "3"); } diff --git a/core-java-concurrency/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java b/core-java-concurrency/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java index 41eb864fd9d9..a1f5b6f1e2e5 100644 --- a/core-java-concurrency/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java +++ b/core-java-concurrency/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java @@ -72,7 +72,7 @@ public void creationSubmittingTasksShuttingDownNow_whenShutDownAfterAwating_then assertTrue(threadPoolExecutor.isShutdown()); assertFalse(notExecutedTasks.isEmpty()); - assertTrue(notExecutedTasks.size() > 0 && notExecutedTasks.size() < 98); + assertTrue(notExecutedTasks.size() < 98); } private List smartShutdown(ExecutorService executorService) { diff --git a/core-java-concurrency/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java b/core-java-concurrency/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java index 42e85fc586b1..502672dea1b9 100644 --- a/core-java-concurrency/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java +++ b/core-java-concurrency/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java @@ -23,7 +23,10 @@ public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() List aList = LongStream.rangeClosed(firstNum, lastNum).boxed().collect(Collectors.toList()); ForkJoinPool customThreadPool = new ForkJoinPool(4); - long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(0L, Long::sum)).get(); + long actualTotal = customThreadPool + .submit(() -> aList.parallelStream() + .reduce(0L, Long::sum)) + .get(); assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal); } diff --git a/pom.xml b/pom.xml index f2dd0ae48c01..da38d65df323 100644 --- a/pom.xml +++ b/pom.xml @@ -43,6 +43,7 @@ cdi core-java + core-java-concurrency couchbase-sdk deltaspike