[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,23 @@
package com.baeldung.concurrent.threadsafety.tests;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.concurrent.threadsafety.callables.CounterCallable;
import com.baeldung.concurrent.threadsafety.services.Counter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CounterTest {
@Test
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
Counter counter = new Counter();
Future<Integer> future1 = (Future<Integer>) executorService.submit(new CounterCallable(counter));
Future<Integer> future2 = (Future<Integer>) executorService.submit(new CounterCallable(counter));
assertThat(future1.get()).isEqualTo(1);
assertThat(future2.get()).isEqualTo(2);
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.concurrent.threadsafety.tests;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.concurrent.threadsafety.callables.ExtrinsicLockCounterCallable;
import com.baeldung.concurrent.threadsafety.services.ExtrinsicLockCounter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ExtrinsicLockCounterTest {
@Test
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
ExtrinsicLockCounter counter = new ExtrinsicLockCounter();
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ExtrinsicLockCounterCallable(counter));
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ExtrinsicLockCounterCallable(counter));
assertThat(future1.get()).isEqualTo(1);
assertThat(future2.get()).isEqualTo(2);
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.concurrent.threadsafety.tests;
import com.baeldung.concurrent.threadsafety.mathutils.MathUtils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class MathUtilsTest {
@Test
public void whenCalledFactorialMethod_thenCorrect() {
assertThat(MathUtils.factorial(2)).isEqualTo(2);
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.concurrent.threadsafety.tests;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import com.baeldung.concurrent.threadsafety.callables.MessageServiceCallable;
import com.baeldung.concurrent.threadsafety.services.MessageService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MessageServiceTest {
@Test
public void whenCalledgetMessage_thenCorrect() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
MessageService messageService = new MessageService("Welcome to Baeldung!");
Future<String> future1 = (Future<String>) executorService.submit(new MessageServiceCallable(messageService));
Future<String> future2 = (Future<String>) executorService.submit(new MessageServiceCallable(messageService));
assertThat(future1.get()).isEqualTo("Welcome to Baeldung!");
assertThat(future2.get()).isEqualTo("Welcome to Baeldung!");
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.concurrent.threadsafety.tests;
import com.baeldung.concurrent.threadsafety.callables.ReentrantLockCounterCallable;
import com.baeldung.concurrent.threadsafety.services.ReentrantLockCounter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class ReentrantLockCounterTest {
@Test
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
ReentrantLockCounter counter = new ReentrantLockCounter();
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ReentrantLockCounterCallable(counter));
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ReentrantLockCounterCallable(counter));
assertThat(future1.get()).isEqualTo(1);
assertThat(future2.get()).isEqualTo(2);
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.concurrent.threadsafety.tests;
import com.baeldung.concurrent.threadsafety.callables.ReentranReadWriteLockCounterCallable;
import com.baeldung.concurrent.threadsafety.services.ReentrantReadWriteLockCounter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class ReentrantReadWriteLockCounterTest {
@Test
public void whenCalledIncrementCounter_thenCorrect() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
ReentrantReadWriteLockCounter counter = new ReentrantReadWriteLockCounter();
Future<Integer> future1 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(counter));
Future<Integer> future2 = (Future<Integer>) executorService.submit(new ReentranReadWriteLockCounterCallable(counter));
assertThat(future1.get()).isEqualTo(1);
assertThat(future2.get()).isEqualTo(2);
}
}

View File

@@ -0,0 +1,208 @@
package com.baeldung.completablefuture;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CompletableFutureLongRunningUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(CompletableFutureLongRunningUnitTest.class);
@Test
public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException {
Future<String> completableFuture = calculateAsync();
String result = completableFuture.get();
assertEquals("Hello", result);
}
private Future<String> calculateAsync() throws InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool()
.submit(() -> {
Thread.sleep(500);
completableFuture.complete("Hello");
return null;
});
return completableFuture;
}
@Test
public void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() throws InterruptedException, ExecutionException {
Future<String> completableFuture = CompletableFuture.completedFuture("Hello");
String result = completableFuture.get();
assertEquals("Hello", result);
}
private Future<String> calculateAsyncWithCancellation() throws InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
Executors.newCachedThreadPool()
.submit(() -> {
Thread.sleep(500);
completableFuture.cancel(false);
return null;
});
return completableFuture;
}
@Test(expected = CancellationException.class)
public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException {
Future<String> future = calculateAsyncWithCancellation();
future.get();
}
@Test
public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello");
assertEquals("Hello", future.get());
}
@Test
public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<Void> future = completableFuture.thenAccept(s -> LOG.debug("Computation returned: " + s));
future.get();
}
@Test
public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<Void> future = completableFuture.thenRun(() -> LOG.debug("Computation finished."));
future.get();
}
@Test
public void whenAddingThenApplyToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future = completableFuture.thenApply(s -> s + " World");
assertEquals("Hello World", future.get());
}
@Test
public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
.thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
assertEquals("Hello World", completableFuture.get());
}
@Test
public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
.thenCombine(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> s1 + s2);
assertEquals("Hello World", completableFuture.get());
}
@Test
public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
CompletableFuture.supplyAsync(() -> "Hello")
.thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"), (s1, s2) -> LOG.debug(s1 + s2));
}
@Test
public void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws ExecutionException, InterruptedException {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Beautiful");
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(future1, future2, future3);
// ...
combinedFuture.get();
assertTrue(future1.isDone());
assertTrue(future2.isDone());
assertTrue(future3.isDone());
String combined = Stream.of(future1, future2, future3)
.map(CompletableFuture::join)
.collect(Collectors.joining(" "));
assertEquals("Hello Beautiful World", combined);
}
@Test
public void whenFutureThrows_thenHandleMethodReceivesException() throws ExecutionException, InterruptedException {
String name = null;
// ...
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
if (name == null) {
throw new RuntimeException("Computation error!");
}
return "Hello, " + name;
})
.handle((s, t) -> s != null ? s : "Hello, Stranger!");
assertEquals("Hello, Stranger!", completableFuture.get());
}
@Test(expected = ExecutionException.class)
public void whenCompletingFutureExceptionally_thenGetMethodThrows() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = new CompletableFuture<>();
// ...
completableFuture.completeExceptionally(new RuntimeException("Calculation failed!"));
// ...
completableFuture.get();
}
@Test
public void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future = completableFuture.thenApplyAsync(s -> s + " World");
assertEquals("Hello World", future.get());
}
@Test
public void whenPassingTransformation_thenFunctionExecutionWithThenApply() throws InterruptedException, ExecutionException {
CompletableFuture<Integer> finalResult = compute().thenApply(s -> s + 1);
assertTrue(finalResult.get() == 11);
}
@Test
public void whenPassingPreviousStage_thenFunctionExecutionWithThenCompose() throws InterruptedException, ExecutionException {
CompletableFuture<Integer> finalResult = compute().thenCompose(this::computeAnother);
assertTrue(finalResult.get() == 20);
}
public CompletableFuture<Integer> compute(){
return CompletableFuture.supplyAsync(() -> 10);
}
public CompletableFuture<Integer> computeAnother(Integer i){
return CompletableFuture.supplyAsync(() -> 10 + i);
}
}

View File

@@ -0,0 +1,48 @@
package com.baeldung.concurrent.callable;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static junit.framework.Assert.assertEquals;
public class FactorialTaskManualTest {
private ExecutorService executorService;
@Before
public void setup(){
executorService = Executors.newSingleThreadExecutor();
}
@Test
public void whenTaskSubmitted_ThenFutureResultObtained() throws ExecutionException, InterruptedException {
FactorialTask task = new FactorialTask(5);
Future<Integer> future= executorService.submit(task);
assertEquals(120,future.get().intValue());
}
@Test(expected = ExecutionException.class)
public void whenException_ThenCallableThrowsIt() throws ExecutionException, InterruptedException {
FactorialTask task = new FactorialTask(-5);
Future<Integer> future= executorService.submit(task);
Integer result=future.get().intValue();
}
@Test
public void whenException_ThenCallableDoesntThrowsItIfGetIsNotCalled(){
FactorialTask task = new FactorialTask(-5);
Future<Integer> future= executorService.submit(task);
assertEquals(false,future.isDone());
}
@After
public void cleanup(){
executorService.shutdown();
}
}

View File

@@ -0,0 +1,145 @@
package com.baeldung.concurrent.executorservice;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
import static junit.framework.TestCase.assertTrue;
public class WaitingForThreadsToFinishManualTest {
private static final Logger LOG = LoggerFactory.getLogger(WaitingForThreadsToFinishManualTest.class);
private final static ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
public void awaitTerminationAfterShutdown(ExecutorService threadPool) {
threadPool.shutdown();
try {
if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {
threadPool.shutdownNow();
}
} catch (InterruptedException ex) {
threadPool.shutdownNow();
Thread.currentThread().interrupt();
}
}
@Test
public void givenMultipleThreads_whenUsingCountDownLatch_thenMainShoudWaitForAllToFinish() {
ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
try {
long startTime = System.currentTimeMillis();
// create a CountDownLatch that waits for the 2 threads to finish
CountDownLatch latch = new CountDownLatch(2);
for (int i = 0; i < 2; i++) {
WORKER_THREAD_POOL.submit(() -> {
try {
Thread.sleep(1000);
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
});
}
// wait for the latch to be decremented by the two threads
latch.await();
long processingTime = System.currentTimeMillis() - startTime;
assertTrue(processingTime >= 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
}
@Test
public void givenMultipleThreads_whenInvokeAll_thenMainThreadShouldWaitForAllToFinish() {
ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
List<Callable<String>> callables = Arrays.asList(
new DelayedCallable("fast thread", 100),
new DelayedCallable("slow thread", 3000));
try {
long startProcessingTime = System.currentTimeMillis();
List<Future<String>> futures = WORKER_THREAD_POOL.invokeAll(callables);
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
try {
WORKER_THREAD_POOL.submit((Callable<String>) () -> {
Thread.sleep(1000000);
return null;
});
} catch (RejectedExecutionException ex) {
//
}
long totalProcessingTime = System.currentTimeMillis() - startProcessingTime;
assertTrue(totalProcessingTime >= 3000);
String firstThreadResponse = futures.get(0)
.get();
assertTrue("First response should be from the fast thread", "fast thread".equals(firstThreadResponse));
String secondThreadResponse = futures.get(1)
.get();
assertTrue("Last response should be from the slow thread", "slow thread".equals(secondThreadResponse));
} catch (ExecutionException | InterruptedException ex) {
ex.printStackTrace();
}
}
@Test
public void givenMultipleThreads_whenUsingCompletionService_thenMainThreadShouldWaitForAllToFinish() {
CompletionService<String> service = new ExecutorCompletionService<>(WORKER_THREAD_POOL);
List<Callable<String>> callables = Arrays.asList(
new DelayedCallable("fast thread", 100),
new DelayedCallable("slow thread", 3000));
for (Callable<String> callable : callables) {
service.submit(callable);
}
try {
long startProcessingTime = System.currentTimeMillis();
Future<String> future = service.take();
String firstThreadResponse = future.get();
long totalProcessingTime = System.currentTimeMillis() - startProcessingTime;
assertTrue("First response should be from the fast thread", "fast thread".equals(firstThreadResponse));
assertTrue(totalProcessingTime >= 100 && totalProcessingTime < 1000);
LOG.debug("Thread finished after: " + totalProcessingTime + " milliseconds");
future = service.take();
String secondThreadResponse = future.get();
totalProcessingTime = System.currentTimeMillis() - startProcessingTime;
assertTrue("Last response should be from the slow thread", "slow thread".equals(secondThreadResponse));
assertTrue(totalProcessingTime >= 3000 && totalProcessingTime < 4000);
LOG.debug("Thread finished after: " + totalProcessingTime + " milliseconds");
} catch (ExecutionException | InterruptedException ex) {
ex.printStackTrace();
} finally {
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
}
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.concurrent.future;
import org.junit.Test;
import java.util.concurrent.ForkJoinPool;
import static org.junit.Assert.assertEquals;
public class FactorialSquareCalculatorUnitTest {
@Test
public void whenCalculatesFactorialSquare_thenReturnCorrectValue() {
ForkJoinPool forkJoinPool = new ForkJoinPool();
FactorialSquareCalculator calculator = new FactorialSquareCalculator(10);
forkJoinPool.execute(calculator);
assertEquals("The sum of the squares from 1 to 10 is 385", 385, calculator.join().intValue());
}
}

View File

@@ -0,0 +1,98 @@
package com.baeldung.concurrent.future;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class SquareCalculatorIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(SquareCalculatorIntegrationTest.class);
@Rule
public TestName name = new TestName();
private long start;
private SquareCalculator squareCalculator;
@Test
public void givenExecutorIsSingleThreaded_whenTwoExecutionsAreTriggered_thenRunInSequence() throws InterruptedException, ExecutionException {
squareCalculator = new SquareCalculator(Executors.newSingleThreadExecutor());
Future<Integer> result1 = squareCalculator.calculate(4);
Future<Integer> result2 = squareCalculator.calculate(1000);
while (!result1.isDone() || !result2.isDone()) {
LOG.debug(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done"));
Thread.sleep(300);
}
assertEquals(16, result1.get().intValue());
assertEquals(1000000, result2.get().intValue());
}
@Test(expected = TimeoutException.class)
public void whenGetWithTimeoutLowerThanExecutionTime_thenThrowException() throws InterruptedException, ExecutionException, TimeoutException {
squareCalculator = new SquareCalculator(Executors.newSingleThreadExecutor());
Future<Integer> result = squareCalculator.calculate(4);
result.get(500, TimeUnit.MILLISECONDS);
}
@Test
public void givenExecutorIsMultiThreaded_whenTwoExecutionsAreTriggered_thenRunInParallel() throws InterruptedException, ExecutionException {
squareCalculator = new SquareCalculator(Executors.newFixedThreadPool(2));
Future<Integer> result1 = squareCalculator.calculate(4);
Future<Integer> result2 = squareCalculator.calculate(1000);
while (!result1.isDone() || !result2.isDone()) {
LOG.debug(String.format("Task 1 is %s and Task 2 is %s.", result1.isDone() ? "done" : "not done", result2.isDone() ? "done" : "not done"));
Thread.sleep(300);
}
assertEquals(16, result1.get().intValue());
assertEquals(1000000, result2.get().intValue());
}
@Test(expected = CancellationException.class)
public void whenCancelFutureAndCallGet_thenThrowException() throws InterruptedException, ExecutionException, TimeoutException {
squareCalculator = new SquareCalculator(Executors.newSingleThreadExecutor());
Future<Integer> result = squareCalculator.calculate(4);
boolean canceled = result.cancel(true);
assertTrue("Future was canceled", canceled);
assertTrue("Future was canceled", result.isCancelled());
result.get();
}
@Before
public void start() {
start = System.currentTimeMillis();
}
@After
public void end() {
LOG.debug(String.format("Test %s took %s ms \n", name.getMethodName(), System.currentTimeMillis() - start));
}
}

View File

@@ -0,0 +1,133 @@
package com.baeldung.concurrent.runnable;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.commons.lang3.RandomUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RunnableVsThreadLiveTest {
private static Logger log =
LoggerFactory.getLogger(RunnableVsThreadLiveTest.class);
private static ExecutorService executorService;
@BeforeClass
public static void setup() {
executorService = Executors.newCachedThreadPool();
}
@Test
public void givenARunnable_whenRunIt_thenResult() throws Exception{
Thread thread = new Thread(new SimpleRunnable(
"SimpleRunnable executed using Thread"));
thread.start();
thread.join();
}
@Test
public void givenARunnable_whenSubmitToES_thenResult() throws Exception{
executorService.submit(new SimpleRunnable(
"SimpleRunnable executed using ExecutorService")).get();
}
@Test
public void givenARunnableLambda_whenSubmitToES_thenResult()
throws Exception{
executorService.submit(()->
log.info("Lambda runnable executed!!!")).get();
}
@Test
public void givenAThread_whenRunIt_thenResult() throws Exception{
Thread thread = new SimpleThread(
"SimpleThread executed using Thread");
thread.start();
thread.join();
}
@Test
public void givenAThread_whenSubmitToES_thenResult() throws Exception{
executorService.submit(new SimpleThread(
"SimpleThread executed using ExecutorService")).get();
}
@Test
public void givenACallable_whenSubmitToES_thenResult() throws Exception {
Future<Integer> future = executorService.submit(
new SimpleCallable());
log.info("Result from callable: {}", future.get());
}
@Test
public void givenACallableAsLambda_whenSubmitToES_thenResult()
throws Exception {
Future<Integer> future = executorService.submit(() -> RandomUtils.nextInt(0, 100));
log.info("Result from callable: {}", future.get());
}
@AfterClass
public static void tearDown() {
if ( executorService != null && !executorService.isShutdown()) {
executorService.shutdown();
}
}
}
class SimpleThread extends Thread{
private static final Logger log =
LoggerFactory.getLogger(SimpleThread.class);
private String message;
SimpleThread(String message) {
this.message = message;
}
@Override
public void run() {
log.info(message);
}
}
class SimpleRunnable implements Runnable {
private static final Logger log =
LoggerFactory.getLogger(SimpleRunnable.class);
private String message;
SimpleRunnable(String message) {
this.message = message;
}
@Override
public void run() {
log.info(message);
}
}
class SimpleCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
return RandomUtils.nextInt(0, 100);
}
}

View File

@@ -0,0 +1,56 @@
package com.baeldung.concurrent.stopping;
import static com.jayway.awaitility.Awaitility.await;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import com.jayway.awaitility.Awaitility;
public class StopThreadManualTest {
@Test
public void whenStoppedThreadIsStopped() throws InterruptedException {
int interval = 5;
ControlSubThread controlSubThread = new ControlSubThread(interval);
controlSubThread.start();
// Give things a chance to get set up
Thread.sleep(interval);
assertTrue(controlSubThread.isRunning());
assertFalse(controlSubThread.isStopped());
// Stop it and make sure the flags have been reversed
controlSubThread.stop();
await()
.until(() -> assertTrue(controlSubThread.isStopped()));
}
@Test
public void whenInterruptedThreadIsStopped() throws InterruptedException {
int interval = 50;
ControlSubThread controlSubThread = new ControlSubThread(interval);
controlSubThread.start();
// Give things a chance to get set up
Thread.sleep(interval);
assertTrue(controlSubThread.isRunning());
assertFalse(controlSubThread.isStopped());
// Stop it and make sure the flags have been reversed
controlSubThread.interrupt();
// Wait less than the time we would normally sleep, and make sure we exited.
Awaitility.await()
.pollDelay(2, TimeUnit.MILLISECONDS)
.atMost(interval/ 10, TimeUnit.MILLISECONDS)
.until(controlSubThread::isStopped);
}
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.concurrent.synchronize;
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;
public class BaeldungSychronizedBlockUnitTest {
@Test
public void givenMultiThread_whenBlockSync() throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(3);
BaeldungSynchronizedBlocks synchronizedBlocks = new BaeldungSynchronizedBlocks();
IntStream.range(0, 1000)
.forEach(count -> service.submit(synchronizedBlocks::performSynchronisedTask));
service.awaitTermination(500, TimeUnit.MILLISECONDS);
assertEquals(1000, synchronizedBlocks.getCount());
}
@Test
public void givenMultiThread_whenStaticSyncBlock() throws InterruptedException {
ExecutorService service = Executors.newCachedThreadPool();
IntStream.range(0, 1000)
.forEach(count -> service.submit(BaeldungSynchronizedBlocks::performStaticSyncTask));
service.awaitTermination(500, TimeUnit.MILLISECONDS);
assertEquals(1000, BaeldungSynchronizedBlocks.getStaticCount());
}
}

View File

@@ -0,0 +1,51 @@
package com.baeldung.concurrent.synchronize;
import org.junit.Ignore;
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;
public class BaeldungSynchronizeMethodsUnitTest {
@Test
@Ignore
public void givenMultiThread_whenNonSyncMethod() throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(3);
BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods();
IntStream.range(0, 1000)
.forEach(count -> service.submit(method::calculate));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, method.getSum());
}
@Test
public void givenMultiThread_whenMethodSync() throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(3);
BaeldungSynchronizedMethods method = new BaeldungSynchronizedMethods();
IntStream.range(0, 1000)
.forEach(count -> service.submit(method::synchronisedCalculate));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, method.getSyncSum());
}
@Test
public void givenMultiThread_whenStaticSyncMethod() throws InterruptedException {
ExecutorService service = Executors.newCachedThreadPool();
IntStream.range(0, 1000)
.forEach(count -> service.submit(BaeldungSynchronizedMethods::syncStaticCalculate));
service.awaitTermination(100, TimeUnit.MILLISECONDS);
assertEquals(1000, BaeldungSynchronizedMethods.staticSum);
}
}

View File

@@ -0,0 +1,66 @@
package com.baeldung.concurrent.waitandnotify;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class NetworkIntegrationTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private String expected;
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}
@Before
public void setUpExpectedOutput() {
StringWriter expectedStringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(expectedStringWriter);
printWriter.println("First packet");
printWriter.println("Second packet");
printWriter.println("Third packet");
printWriter.println("Fourth packet");
printWriter.close();
expected = expectedStringWriter.toString();
}
@After
public void cleanUpStreams() {
System.setOut(null);
System.setErr(null);
}
@Test
public void givenSenderAndReceiver_whenSendingPackets_thenNetworkSynchronized() {
Data data = new Data();
Thread sender = new Thread(new Sender(data));
Thread receiver = new Thread(new Receiver(data));
sender.start();
receiver.start();
//wait for sender and receiver to finish before we test against expected
try {
sender.join();
receiver.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Thread Interrupted");
}
assertEquals(expected, outContent.toString());
}
}

View File

@@ -0,0 +1,162 @@
package com.baeldung.java8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Before;
import org.junit.Test;
public class Java8ExecutorServiceIntegrationTest {
private Runnable runnableTask;
private Callable<String> callableTask;
private List<Callable<String>> callableTasks;
@Before
public void init() {
runnableTask = () -> {
try {
TimeUnit.MILLISECONDS.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
callableTask = () -> {
TimeUnit.MILLISECONDS.sleep(300);
return "Task's execution";
};
callableTasks = new ArrayList<>();
callableTasks.add(callableTask);
callableTasks.add(callableTask);
callableTasks.add(callableTask);
}
@Test
public void creationSubmittingTaskShuttingDown_whenShutDown_thenCorrect() {
ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.submit(runnableTask);
executorService.submit(callableTask);
executorService.shutdown();
assertTrue(executorService.isShutdown());
}
@Test
public void creationSubmittingTasksShuttingDownNow_whenShutDownAfterAwating_thenCorrect() {
ExecutorService threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
for (int i = 0; i < 100; i++) {
threadPoolExecutor.submit(callableTask);
}
List<Runnable> notExecutedTasks = smartShutdown(threadPoolExecutor);
assertTrue(threadPoolExecutor.isShutdown());
assertFalse(notExecutedTasks.isEmpty());
assertTrue(notExecutedTasks.size() < 98);
}
private List<Runnable> smartShutdown(ExecutorService executorService) {
List<Runnable> notExecutedTasks = new ArrayList<>();
executorService.shutdown();
try {
if (!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)) {
notExecutedTasks = executorService.shutdownNow();
}
} catch (InterruptedException e) {
notExecutedTasks = executorService.shutdownNow();
}
return notExecutedTasks;
}
@Test
public void submittingTasks_whenExecutedOneAndAll_thenCorrect() {
ExecutorService executorService = Executors.newFixedThreadPool(10);
String result = null;
List<Future<String>> futures = new ArrayList<>();
try {
result = executorService.invokeAny(callableTasks);
futures = executorService.invokeAll(callableTasks);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
assertEquals("Task's execution", result);
assertTrue(futures.size() == 3);
}
@Test
public void submittingTaskShuttingDown_whenGetExpectedResult_thenCorrect() {
ExecutorService executorService = Executors.newFixedThreadPool(10);
Future<String> future = executorService.submit(callableTask);
String result = null;
try {
result = future.get();
result = future.get(200, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();
}
executorService.shutdown();
assertEquals("Task's execution", result);
}
@Test
public void submittingTask_whenCanceled_thenCorrect() {
ExecutorService executorService = Executors.newFixedThreadPool(10);
Future<String> future = executorService.submit(callableTask);
boolean canceled = future.cancel(true);
boolean isCancelled = future.isCancelled();
executorService.shutdown();
assertTrue(canceled);
assertTrue(isCancelled);
}
@Test
public void submittingTaskScheduling_whenExecuted_thenCorrect() {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
Future<String> resultFuture = executorService.schedule(callableTask, 1, TimeUnit.SECONDS);
String result = null;
try {
result = resultFuture.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executorService.shutdown();
assertEquals("Task's execution", result);
}
}

View File

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