[BAEL-9555] - Created a core-java-modules folder

This commit is contained in:
amit2103
2019-05-05 17:22:09 +05:30
parent 8b63b0d90a
commit 3bae5e5334
1480 changed files with 25600 additions and 5594 deletions

View File

@@ -0,0 +1,38 @@
package com.baeldung.concurrent.accumulator;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.function.LongBinaryOperator;
import java.util.stream.IntStream;
import static junit.framework.TestCase.assertEquals;
public class LongAccumulatorUnitTest {
@Test
public void givenLongAccumulator_whenApplyActionOnItFromMultipleThrads_thenShouldProduceProperResult() throws InterruptedException {
// given
ExecutorService executorService = Executors.newFixedThreadPool(8);
LongBinaryOperator sum = Long::sum;
LongAccumulator accumulator = new LongAccumulator(sum, 0L);
int numberOfThreads = 4;
int numberOfIncrements = 100;
// when
Runnable accumulateAction = () -> IntStream.rangeClosed(0, numberOfIncrements).forEach(accumulator::accumulate);
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(accumulateAction);
}
// then
executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
executorService.shutdown();
assertEquals(accumulator.get(), 20200);
}
}

View File

@@ -0,0 +1,67 @@
package com.baeldung.concurrent.adder;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.IntStream;
import static com.jayway.awaitility.Awaitility.await;
import static junit.framework.TestCase.assertEquals;
public class LongAdderUnitTest {
@Test
public void givenMultipleThread_whenTheyWriteToSharedLongAdder_thenShouldCalculateSumForThem() throws InterruptedException {
//given
LongAdder counter = new LongAdder();
ExecutorService executorService = Executors.newFixedThreadPool(8);
int numberOfThreads = 4;
int numberOfIncrements = 100;
//when
Runnable incrementAction = () -> IntStream
.range(0, numberOfIncrements)
.forEach((i) -> counter.increment());
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(incrementAction);
}
//then
executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
executorService.shutdown();
assertEquals(counter.sum(), numberOfIncrements * numberOfThreads);
assertEquals(counter.sum(), numberOfIncrements * numberOfThreads);
}
@Test
public void givenMultipleThread_whenTheyWriteToSharedLongAdder_thenShouldCalculateSumForThemAndResetAdderAfterward() throws InterruptedException {
//given
LongAdder counter = new LongAdder();
ExecutorService executorService = Executors.newFixedThreadPool(8);
int numberOfThreads = 4;
int numberOfIncrements = 100;
//when
Runnable incrementAction = () -> IntStream
.range(0, numberOfIncrements)
.forEach((i) -> counter.increment());
for (int i = 0; i < numberOfThreads; i++) {
executorService.execute(incrementAction);
}
//then
executorService.awaitTermination(500, TimeUnit.MILLISECONDS);
executorService.shutdown();
assertEquals(counter.sumThenReset(), numberOfIncrements * numberOfThreads);
await().until(() -> assertEquals(counter.sum(), 0));
}
}

View File

@@ -0,0 +1,38 @@
package com.baeldung.concurrent.atomic;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.Test;
public class ThreadSafeCounterIntegrationTest {
@Test
public void givenMultiThread_whenSafeCounterWithLockIncrement() throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(3);
SafeCounterWithLock safeCounter = new SafeCounterWithLock();
IntStream.range(0, 1000)
.forEach(count -> service.submit(safeCounter::increment));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, safeCounter.getValue());
}
@Test
public void givenMultiThread_whenSafeCounterWithoutLockIncrement() throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(3);
SafeCounterWithoutLock safeCounter = new SafeCounterWithoutLock();
IntStream.range(0, 1000)
.forEach(count -> service.submit(safeCounter::increment));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, safeCounter.getValue());
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.concurrent.atomic;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.Test;
/**
* This test shows the behaviour of a thread-unsafe class in a multithreaded scenario. We are calling
* the increment methods 1000 times from a pool of 3 threads. In most of the cases, the counter will
* less than 1000, because of lost updates, however, occasionally it may reach 1000, when no threads
* called the method simultaneously. This may cause the build to fail occasionally. Hence excluding this
* test from build by adding this in manual test
*/
public class ThreadUnsafeCounterManualTest {
@Test
public void givenMultiThread_whenUnsafeCounterIncrement() throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(3);
UnsafeCounter unsafeCounter = new UnsafeCounter();
IntStream.range(0, 1000)
.forEach(count -> service.submit(unsafeCounter::increment));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, unsafeCounter.getValue());
}
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.concurrent.countdownlatch;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CountdownLatchCountExampleUnitTest {
@Test
public void whenCountDownLatch_completed() {
CountdownLatchCountExample ex = new CountdownLatchCountExample(2);
boolean isCompleted = ex.callTwiceInSameThread();
assertTrue(isCompleted);
}
}

View File

@@ -0,0 +1,72 @@
package com.baeldung.concurrent.countdownlatch;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThat;
public class CountdownLatchExampleIntegrationTest {
@Test
public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion() throws InterruptedException {
// Given
List<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
CountDownLatch countDownLatch = new CountDownLatch(5);
List<Thread> workers = Stream.generate(() -> new Thread(new Worker(outputScraper, countDownLatch)))
.limit(5)
.collect(toList());
// When
workers.forEach(Thread::start);
countDownLatch.await(); // Block until workers finish
outputScraper.add("Latch released");
// Then
assertThat(outputScraper).containsExactly("Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Latch released");
}
@Test
public void whenFailingToParallelProcess_thenMainThreadShouldTimeout() throws InterruptedException {
// Given
List<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
CountDownLatch countDownLatch = new CountDownLatch(5);
List<Thread> workers = Stream.generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch)))
.limit(5)
.collect(toList());
// When
workers.forEach(Thread::start);
final boolean result = countDownLatch.await(3L, TimeUnit.SECONDS);
// Then
assertThat(result).isFalse();
}
@Test
public void whenDoingLotsOfThreadsInParallel_thenStartThemAtTheSameTime() throws InterruptedException {
// Given
List<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
CountDownLatch readyThreadCounter = new CountDownLatch(5);
CountDownLatch callingThreadBlocker = new CountDownLatch(1);
CountDownLatch completedThreadCounter = new CountDownLatch(5);
List<Thread> workers = Stream.generate(() -> new Thread(new WaitingWorker(outputScraper, readyThreadCounter, callingThreadBlocker, completedThreadCounter))).limit(5).collect(toList());
// When
workers.forEach(Thread::start);
readyThreadCounter.await(); // Block until workers start
outputScraper.add("Workers ready");
callingThreadBlocker.countDown(); // Start workers
completedThreadCounter.await(); // Block until workers finish
outputScraper.add("Workers complete");
// Then
assertThat(outputScraper).containsExactly("Workers ready", "Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Workers complete");
}
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.concurrent.countdownlatch;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CountdownLatchResetExampleUnitTest {
@Test
public void whenCountDownLatch_noReset() {
CountdownLatchResetExample ex = new CountdownLatchResetExample(7,20);
int lineCount = ex.countWaits();
assertTrue(lineCount <= 7);
}
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.concurrent.cyclicbarrier;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CyclicBarrierCompletionMethodExampleUnitTest {
@Test
public void whenCyclicBarrier_countTrips() {
CyclicBarrierCompletionMethodExample ex = new CyclicBarrierCompletionMethodExample(7,20);
int lineCount = ex.countTrips();
assertEquals(2, lineCount);
}
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.concurrent.cyclicbarrier;
import static org.junit.Assert.assertFalse;
import org.junit.Test;
public class CyclicBarrierCountExampleUnitTest {
@Test
public void whenCyclicBarrier_notCompleted() {
CyclicBarrierCountExample ex = new CyclicBarrierCountExample(2);
boolean isCompleted = ex.callTwiceInSameThread();
assertFalse(isCompleted);
}
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.concurrent.cyclicbarrier;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class CyclicBarrierResetExampleUnitTest {
@Test
public void whenCyclicBarrier_reset() {
CyclicBarrierResetExample ex = new CyclicBarrierResetExample(7,20);
int lineCount = ex.countWaits();
assertTrue(lineCount > 7);
}
}

View File

@@ -0,0 +1,31 @@
package com.baeldung.concurrent.daemon;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Ignore;
import org.junit.Test;
public class DaemonThreadUnitTest {
@Test
@Ignore
public void whenCallIsDaemon_thenCorrect() {
NewThread daemonThread = new NewThread();
NewThread userThread = new NewThread();
daemonThread.setDaemon(true);
daemonThread.start();
userThread.start();
assertTrue(daemonThread.isDaemon());
assertFalse(userThread.isDaemon());
}
@Test(expected = IllegalThreadStateException.class)
@Ignore
public void givenUserThread_whenSetDaemonWhileRunning_thenIllegalThreadStateException() {
NewThread daemonThread = new NewThread();
daemonThread.start();
daemonThread.setDaemon(true);
}
}

View File

@@ -0,0 +1,73 @@
package com.baeldung.concurrent.locks;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static junit.framework.TestCase.assertEquals;
public class SharedObjectWithLockManualTest {
@Test
public void whenLockAcquired_ThenLockedIsTrue() {
final SharedObjectWithLock object = new SharedObjectWithLock();
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeThreads(object, threadCount, service);
assertEquals(true, object.isLocked());
service.shutdown();
}
@Test
public void whenLocked_ThenQueuedThread() {
final int threadCount = 4;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final SharedObjectWithLock object = new SharedObjectWithLock();
executeThreads(object, threadCount, service);
assertEquals(object.hasQueuedThreads(), true);
service.shutdown();
}
public void whenTryLock_ThenQueuedThread() {
final SharedObjectWithLock object = new SharedObjectWithLock();
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeThreads(object, threadCount, service);
assertEquals(true, object.isLocked());
service.shutdown();
}
@Test
public void whenGetCount_ThenCorrectCount() throws InterruptedException {
final int threadCount = 4;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final SharedObjectWithLock object = new SharedObjectWithLock();
executeThreads(object, threadCount, service);
Thread.sleep(1000);
assertEquals(object.getCounter(), 4);
service.shutdown();
}
private void executeThreads(SharedObjectWithLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++) {
service.execute(object::perform);
}
}
}

View File

@@ -0,0 +1,55 @@
package com.baeldung.concurrent.locks;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static junit.framework.TestCase.assertEquals;
public class SynchronizedHashMapWithRWLockManualTest {
@Test
public void whenWriting_ThenNoReading() {
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
final int threadCount = 3;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeWriterThreads(object, threadCount, service);
assertEquals(object.isReadLockAvailable(), false);
service.shutdown();
}
@Test
public void whenReading_ThenMultipleReadingAllowed() {
SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock();
final int threadCount = 5;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
executeReaderThreads(object, threadCount, service);
assertEquals(object.isReadLockAvailable(), true);
service.shutdown();
}
private void executeWriterThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++) {
service.execute(() -> {
try {
object.put("key" + threadCount, "value" + threadCount);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
private void executeReaderThreads(SynchronizedHashMapWithRWLock object, int threadCount, ExecutorService service) {
for (int i = 0; i < threadCount; i++)
service.execute(() -> object.get("key" + threadCount));
}
}

View File

@@ -0,0 +1,41 @@
package com.baeldung.concurrent.phaser;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;
import static junit.framework.TestCase.assertEquals;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class PhaserUnitTest {
@Test
public void givenPhaser_whenCoordinateWorksBetweenThreads_thenShouldCoordinateBetweenMultiplePhases() {
//given
ExecutorService executorService = Executors.newCachedThreadPool();
Phaser ph = new Phaser(1);
assertEquals(0, ph.getPhase());
//when
executorService.submit(new LongRunningAction("thread-1", ph));
executorService.submit(new LongRunningAction("thread-2", ph));
executorService.submit(new LongRunningAction("thread-3", ph));
//then
ph.arriveAndAwaitAdvance();
assertEquals(1, ph.getPhase());
//and
executorService.submit(new LongRunningAction("thread-4", ph));
executorService.submit(new LongRunningAction("thread-5", ph));
ph.arriveAndAwaitAdvance();
assertEquals(2, ph.getPhase());
ph.arriveAndDeregister();
}
}

View File

@@ -0,0 +1,40 @@
package com.baeldung.concurrent.prioritytaskexecution;
import org.junit.Test;
public class PriorityJobSchedulerUnitTest {
private static int POOL_SIZE = 1;
private static int QUEUE_SIZE = 10;
@Test
public void whenMultiplePriorityJobsQueued_thenHighestPriorityJobIsPicked() {
Job job1 = new Job("Job1", JobPriority.LOW);
Job job2 = new Job("Job2", JobPriority.MEDIUM);
Job job3 = new Job("Job3", JobPriority.HIGH);
Job job4 = new Job("Job4", JobPriority.MEDIUM);
Job job5 = new Job("Job5", JobPriority.LOW);
Job job6 = new Job("Job6", JobPriority.HIGH);
PriorityJobScheduler pjs = new PriorityJobScheduler(POOL_SIZE, QUEUE_SIZE);
pjs.scheduleJob(job1);
pjs.scheduleJob(job2);
pjs.scheduleJob(job3);
pjs.scheduleJob(job4);
pjs.scheduleJob(job5);
pjs.scheduleJob(job6);
// ensure no tasks is pending before closing the scheduler
while (pjs.getQueuedTaskCount() != 0);
// delay to avoid job sleep (added for demo) being interrupted
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
pjs.closeScheduler();
}
}

View File

@@ -0,0 +1,119 @@
package com.baeldung.concurrent.semaphores;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SemaphoresManualTest {
// ========= login queue ======
@Test
public void givenLoginQueue_whenReachLimit_thenBlocked() throws InterruptedException {
final int slots = 10;
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
final LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);
IntStream.range(0, slots)
.forEach(user -> executorService.execute(loginQueue::tryLogin));
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);
assertEquals(0, loginQueue.availableSlots());
assertFalse(loginQueue.tryLogin());
}
@Test
public void givenLoginQueue_whenLogout_thenSlotsAvailable() throws InterruptedException {
final int slots = 10;
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
final LoginQueueUsingSemaphore loginQueue = new LoginQueueUsingSemaphore(slots);
IntStream.range(0, slots)
.forEach(user -> executorService.execute(loginQueue::tryLogin));
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);
assertEquals(0, loginQueue.availableSlots());
loginQueue.logout();
assertTrue(loginQueue.availableSlots() > 0);
assertTrue(loginQueue.tryLogin());
}
// ========= delay queue =======
@Test
public void givenDelayQueue_whenReachLimit_thenBlocked() throws InterruptedException {
final int slots = 50;
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
final DelayQueueUsingTimedSemaphore delayQueue = new DelayQueueUsingTimedSemaphore(1, slots);
IntStream.range(0, slots)
.forEach(user -> executorService.execute(delayQueue::tryAdd));
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);
assertEquals(0, delayQueue.availableSlots());
assertFalse(delayQueue.tryAdd());
}
@Test
public void givenDelayQueue_whenTimePass_thenSlotsAvailable() throws InterruptedException {
final int slots = 50;
final ExecutorService executorService = Executors.newFixedThreadPool(slots);
final DelayQueueUsingTimedSemaphore delayQueue = new DelayQueueUsingTimedSemaphore(1, slots);
IntStream.range(0, slots)
.forEach(user -> executorService.execute(delayQueue::tryAdd));
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);
assertEquals(0, delayQueue.availableSlots());
Thread.sleep(1000);
assertTrue(delayQueue.availableSlots() > 0);
assertTrue(delayQueue.tryAdd());
}
// ========== mutex ========
@Test
public void whenMutexAndMultipleThreads_thenBlocked() throws InterruptedException {
final int count = 5;
final ExecutorService executorService = Executors.newFixedThreadPool(count);
final CounterUsingMutex counter = new CounterUsingMutex();
IntStream.range(0, count)
.forEach(user -> executorService.execute(() -> {
try {
counter.increase();
} catch (final InterruptedException e) {
e.printStackTrace();
}
}));
executorService.shutdown();
assertTrue(counter.hasQueuedThreads());
}
@Test
public void givenMutexAndMultipleThreads_ThenDelay_thenCorrectCount() throws InterruptedException {
final int count = 5;
final ExecutorService executorService = Executors.newFixedThreadPool(count);
final CounterUsingMutex counter = new CounterUsingMutex();
IntStream.range(0, count)
.forEach(user -> executorService.execute(() -> {
try {
counter.increase();
} catch (final InterruptedException e) {
e.printStackTrace();
}
}));
executorService.shutdown();
assertTrue(counter.hasQueuedThreads());
Thread.sleep(5000);
assertFalse(counter.hasQueuedThreads());
assertEquals(count, counter.getCount());
}
}

View File

@@ -0,0 +1,55 @@
package com.baeldung.concurrent.volatilekeyword;
import org.junit.Test;
import static org.junit.Assert.*;
public class SharedObjectManualTest {
@Test
public void whenOneThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException {
SharedObject sharedObject = new SharedObject();
Thread writer = new Thread(() -> sharedObject.increamentCount());
writer.start();
Thread.sleep(100);
Thread readerOne = new Thread(() -> {
int valueReadByThread2 = sharedObject.getCount();
assertEquals(1, valueReadByThread2);
});
readerOne.start();
Thread readerTwo = new Thread(() -> {
int valueReadByThread3 = sharedObject.getCount();
assertEquals(1, valueReadByThread3);
});
readerTwo.start();
}
@Test
public void whenTwoThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException {
SharedObject sharedObject = new SharedObject();
Thread writerOne = new Thread(() -> sharedObject.increamentCount());
writerOne.start();
Thread.sleep(100);
Thread writerTwo = new Thread(() -> sharedObject.increamentCount());
writerTwo.start();
Thread.sleep(100);
Thread readerOne = new Thread(() -> {
int valueReadByThread2 = sharedObject.getCount();
assertEquals(2, valueReadByThread2);
});
readerOne.start();
Thread readerTwo = new Thread(() -> {
int valueReadByThread3 = sharedObject.getCount();
assertEquals(2, valueReadByThread3);
});
readerTwo.start();
}
}

View File

@@ -0,0 +1,94 @@
package com.baeldung.java8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.forkjoin.CustomRecursiveAction;
import com.baeldung.forkjoin.CustomRecursiveTask;
import com.baeldung.forkjoin.util.PoolUtil;
public class Java8ForkJoinIntegrationTest {
private int[] arr;
private CustomRecursiveTask customRecursiveTask;
@Before
public void init() {
Random random = new Random();
arr = new int[50];
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(35);
}
customRecursiveTask = new CustomRecursiveTask(arr);
}
@Test
public void callPoolUtil_whenExistsAndExpectedType_thenCorrect() {
ForkJoinPool forkJoinPool = PoolUtil.forkJoinPool;
ForkJoinPool forkJoinPoolTwo = PoolUtil.forkJoinPool;
assertNotNull(forkJoinPool);
assertEquals(2, forkJoinPool.getParallelism());
assertEquals(forkJoinPool, forkJoinPoolTwo);
}
@Test
public void callCommonPool_whenExistsAndExpectedType_thenCorrect() {
ForkJoinPool commonPool = ForkJoinPool.commonPool();
ForkJoinPool commonPoolTwo = ForkJoinPool.commonPool();
assertNotNull(commonPool);
assertEquals(commonPool, commonPoolTwo);
}
@Test
public void executeRecursiveAction_whenExecuted_thenCorrect() {
CustomRecursiveAction myRecursiveAction = new CustomRecursiveAction("ddddffffgggghhhh");
ForkJoinPool.commonPool().invoke(myRecursiveAction);
assertTrue(myRecursiveAction.isDone());
}
@Test
public void executeRecursiveTask_whenExecuted_thenCorrect() {
ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
forkJoinPool.execute(customRecursiveTask);
int result = customRecursiveTask.join();
assertTrue(customRecursiveTask.isDone());
forkJoinPool.submit(customRecursiveTask);
int resultTwo = customRecursiveTask.join();
assertTrue(customRecursiveTask.isDone());
}
@Test
public void executeRecursiveTaskWithFJ_whenExecuted_thenCorrect() {
CustomRecursiveTask customRecursiveTaskFirst = new CustomRecursiveTask(arr);
CustomRecursiveTask customRecursiveTaskSecond = new CustomRecursiveTask(arr);
CustomRecursiveTask customRecursiveTaskLast = new CustomRecursiveTask(arr);
customRecursiveTaskFirst.fork();
customRecursiveTaskSecond.fork();
customRecursiveTaskLast.fork();
int result = 0;
result += customRecursiveTaskLast.join();
result += customRecursiveTaskSecond.join();
result += customRecursiveTaskFirst.join();
assertTrue(customRecursiveTaskFirst.isDone());
assertTrue(customRecursiveTaskSecond.isDone());
assertTrue(customRecursiveTaskLast.isDone());
assertTrue(result != 0);
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.parameters;
import com.baeldung.concurrent.parameter.AverageCalculator;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
public class ParameterizedThreadUnitTest {
@Test
public void whenSendingParameterToCallable_thenSuccessful() throws Exception {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Double> result = executorService.submit(new AverageCalculator(1, 2, 3));
try {
assertEquals(Double.valueOf(2.0), result.get());
} finally {
executorService.shutdown();
}
}
@Test
public void whenParametersToThreadWithLamda_thenParametersPassedCorrectly() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
int[] numbers = new int[] { 4, 5, 6 };
try {
Future<Integer> sumResult = executorService.submit(() -> IntStream.of(numbers)
.sum());
Future<Double> averageResult = executorService.submit(() -> IntStream.of(numbers)
.average()
.orElse(0d));
assertEquals(Integer.valueOf(15), sumResult.get());
assertEquals(Double.valueOf(5.0), averageResult.get());
} finally {
executorService.shutdown();
}
}
}

View File

@@ -0,0 +1,95 @@
package com.baeldung.thread.join;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.logging.Logger;
import org.junit.Ignore;
import org.junit.Test;
/**
* Demonstrates Thread.join behavior.
*
*/
public class ThreadJoinUnitTest {
final static Logger LOGGER = Logger.getLogger(ThreadJoinUnitTest.class.getName());
class SampleThread extends Thread {
public int processingCount = 0;
SampleThread(int processingCount) {
this.processingCount = processingCount;
LOGGER.info("Thread " + this.getName() + " created");
}
@Override
public void run() {
LOGGER.info("Thread " + this.getName() + " started");
while (processingCount > 0) {
try {
Thread.sleep(1000); // Simulate some work being done by thread
} catch (InterruptedException e) {
LOGGER.info("Thread " + this.getName() + " interrupted.");
}
processingCount--;
LOGGER.info("Inside Thread " + this.getName() + ", processingCount = " + processingCount);
}
LOGGER.info("Thread " + this.getName() + " exiting");
}
}
@Test
public void givenNewThread_whenJoinCalled_returnsImmediately() throws InterruptedException {
Thread t1 = new SampleThread(0);
LOGGER.info("Invoking join.");
t1.join();
LOGGER.info("Returned from join");
LOGGER.info("Thread state is" + t1.getState());
assertFalse(t1.isAlive());
}
@Test
public void givenStartedThread_whenJoinCalled_waitsTillCompletion()
throws InterruptedException {
Thread t2 = new SampleThread(1);
t2.start();
LOGGER.info("Invoking join.");
t2.join();
LOGGER.info("Returned from join");
assertFalse(t2.isAlive());
}
@Test
public void givenStartedThread_whenTimedJoinCalled_waitsUntilTimedout()
throws InterruptedException {
Thread t3 = new SampleThread(10);
t3.start();
t3.join(1000);
assertTrue(t3.isAlive());
}
@Test
@Ignore
public void givenThreadTerminated_checkForEffect_notGuaranteed()
throws InterruptedException {
SampleThread t4 = new SampleThread(10);
t4.start();
//not guaranteed to stop even if t4 finishes.
do {
} while (t4.processingCount > 0);
}
@Test
public void givenJoinWithTerminatedThread_checkForEffect_guaranteed()
throws InterruptedException {
SampleThread t4 = new SampleThread(10);
t4.start();
do {
t4.join(100);
} while (t4.processingCount > 0);
}
}

View File

@@ -0,0 +1,35 @@
package com.baeldung.threadlocal;
import org.junit.Test;
import java.util.concurrent.ExecutionException;
import static org.junit.Assert.assertEquals;
public class ThreadLocalIntegrationTest {
@Test
public void givenThreadThatStoresContextInAMap_whenStartThread_thenShouldSetContextForBothUsers() throws ExecutionException, InterruptedException {
//when
SharedMapWithUserContext firstUser = new SharedMapWithUserContext(1);
SharedMapWithUserContext secondUser = new SharedMapWithUserContext(2);
new Thread(firstUser).start();
new Thread(secondUser).start();
Thread.sleep(3000);
//then
assertEquals(SharedMapWithUserContext.userContextPerUserId.size(), 2);
}
@Test
public void givenThreadThatStoresContextInThreadLocal_whenStartThread_thenShouldStoreContextInThreadLocal() throws ExecutionException, InterruptedException {
//when
ThreadLocalWithUserContext firstUser = new ThreadLocalWithUserContext(1);
ThreadLocalWithUserContext secondUser = new ThreadLocalWithUserContext(2);
new Thread(firstUser).start();
new Thread(secondUser).start();
Thread.sleep(3000);
}
}

View File

@@ -0,0 +1,63 @@
package com.baeldung.threadlocalrandom;
import java.util.concurrent.ThreadLocalRandom;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ThreadLocalRandomIntegrationTest {
@Test
public void givenUsingThreadLocalRandom_whenGeneratingRandomIntBounded_thenCorrect() {
int leftLimit = 1;
int rightLimit = 100;
int generatedInt = ThreadLocalRandom.current().nextInt(leftLimit, rightLimit);
assertTrue(generatedInt < rightLimit && generatedInt >= leftLimit);
}
@Test
public void givenUsingThreadLocalRandom_whenGeneratingRandomIntUnbounded_thenCorrect() {
int generatedInt = ThreadLocalRandom.current().nextInt();
assertTrue(generatedInt < Integer.MAX_VALUE && generatedInt >= Integer.MIN_VALUE);
}
@Test
public void givenUsingThreadLocalRandom_whenGeneratingRandomLongBounded_thenCorrect() {
long leftLimit = 1L;
long rightLimit = 100L;
long generatedLong = ThreadLocalRandom.current().nextLong(leftLimit, rightLimit);
assertTrue(generatedLong < rightLimit && generatedLong >= leftLimit);
}
@Test
public void givenUsingThreadLocalRandom_whenGeneratingRandomLongUnbounded_thenCorrect() {
long generatedInt = ThreadLocalRandom.current().nextLong();
assertTrue(generatedInt < Long.MAX_VALUE && generatedInt >= Long.MIN_VALUE);
}
@Test
public void givenUsingThreadLocalRandom_whenGeneratingRandomDoubleBounded_thenCorrect() {
double leftLimit = 1D;
double rightLimit = 100D;
double generatedInt = ThreadLocalRandom.current().nextDouble(leftLimit, rightLimit);
assertTrue(generatedInt < rightLimit && generatedInt >= leftLimit);
}
@Test
public void givenUsingThreadLocalRandom_whenGeneratingRandomDoubleUnbounded_thenCorrect() {
double generatedInt = ThreadLocalRandom.current().nextDouble();
assertTrue(generatedInt < Double.MAX_VALUE && generatedInt >= Double.MIN_VALUE);
}
@Test(expected = UnsupportedOperationException.class)
public void givenUsingThreadLocalRandom_whenSettingSeed_thenThrowUnsupportedOperationException() {
ThreadLocalRandom.current().setSeed(0l);
}
}

View File

@@ -0,0 +1,147 @@
package com.baeldung.threadpool;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
public class CoreThreadPoolIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(CoreThreadPoolIntegrationTest.class);
@Test(timeout = 1000)
public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException {
CountDownLatch lock = new CountDownLatch(1);
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(() -> {
LOG.debug("Hello World");
lock.countDown();
});
lock.await(1000, TimeUnit.MILLISECONDS);
}
@Test
public void whenUsingExecutorServiceAndFuture_thenCanWaitOnFutureResult() throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
Future<String> future = executorService.submit(() -> "Hello World");
String result = future.get();
assertEquals("Hello World", result);
}
@Test
public void whenUsingFixedThreadPool_thenCoreAndMaximumThreadSizeAreTheSame() {
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
executor.submit(() -> {
Thread.sleep(1000);
return null;
});
executor.submit(() -> {
Thread.sleep(1000);
return null;
});
executor.submit(() -> {
Thread.sleep(1000);
return null;
});
assertEquals(2, executor.getPoolSize());
assertEquals(1, executor.getQueue().size());
}
@Test
public void whenUsingCachedThreadPool_thenPoolSizeGrowsUnbounded() {
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
executor.submit(() -> {
Thread.sleep(1000);
return null;
});
executor.submit(() -> {
Thread.sleep(1000);
return null;
});
executor.submit(() -> {
Thread.sleep(1000);
return null;
});
assertEquals(3, executor.getPoolSize());
assertEquals(0, executor.getQueue().size());
}
@Test(timeout = 1000)
public void whenUsingSingleThreadPool_thenTasksExecuteSequentially() throws InterruptedException {
CountDownLatch lock = new CountDownLatch(2);
AtomicInteger counter = new AtomicInteger();
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
counter.set(1);
lock.countDown();
});
executor.submit(() -> {
counter.compareAndSet(1, 2);
lock.countDown();
});
lock.await(1000, TimeUnit.MILLISECONDS);
assertEquals(2, counter.get());
}
@Test(timeout = 1000)
public void whenSchedulingTask_thenTaskExecutesWithinGivenPeriod() throws InterruptedException {
CountDownLatch lock = new CountDownLatch(1);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
executor.schedule(() -> {
LOG.debug("Hello World");
lock.countDown();
}, 500, TimeUnit.MILLISECONDS);
lock.await(1000, TimeUnit.MILLISECONDS);
}
@Test(timeout = 1000)
public void whenSchedulingTaskWithFixedPeriod_thenTaskExecutesMultipleTimes() throws InterruptedException {
CountDownLatch lock = new CountDownLatch(3);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
ScheduledFuture<?> future = executor.scheduleAtFixedRate(() -> {
LOG.debug("Hello World");
lock.countDown();
}, 500, 100, TimeUnit.MILLISECONDS);
lock.await();
future.cancel(true);
}
@Test
public void whenUsingForkJoinPool_thenSumOfTreeElementsIsCalculatedCorrectly() {
TreeNode tree = new TreeNode(5, new TreeNode(3), new TreeNode(2, new TreeNode(2), new TreeNode(8)));
ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
int sum = forkJoinPool.invoke(new CountingTask(tree));
assertEquals(20, sum);
}
}

View File

@@ -0,0 +1,54 @@
package com.baeldung.threadpool;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class GuavaThreadPoolIntegrationTest {
@Test
public void whenExecutingTaskWithDirectExecutor_thenTheTaskIsExecutedInTheCurrentThread() {
Executor executor = MoreExecutors.directExecutor();
AtomicBoolean executed = new AtomicBoolean();
executor.execute(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
executed.set(true);
});
assertTrue(executed.get());
}
@Test
public void whenJoiningFuturesWithAllAsList_thenCombinedFutureCompletesAfterAllFuturesComplete() throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService);
ListenableFuture<String> future1 = listeningExecutorService.submit(() -> "Hello");
ListenableFuture<String> future2 = listeningExecutorService.submit(() -> "World");
String greeting = Futures.allAsList(future1, future2).get().stream().collect(Collectors.joining(" "));
assertEquals("Hello World", greeting);
}
}

View File

@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear