|
| 1 | +package com.baeldung.threadpool; |
| 2 | + |
| 3 | +import java.util.concurrent.ExecutionException; |
| 4 | +import java.util.concurrent.Executor; |
| 5 | +import java.util.concurrent.ExecutorService; |
| 6 | +import java.util.concurrent.Executors; |
| 7 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 8 | +import java.util.stream.Collectors; |
| 9 | + |
| 10 | +import com.google.common.util.concurrent.Futures; |
| 11 | +import com.google.common.util.concurrent.ListenableFuture; |
| 12 | +import com.google.common.util.concurrent.ListeningExecutorService; |
| 13 | +import com.google.common.util.concurrent.MoreExecutors; |
| 14 | +import org.junit.Test; |
| 15 | + |
| 16 | +import static org.junit.Assert.assertEquals; |
| 17 | +import static org.junit.Assert.assertTrue; |
| 18 | + |
| 19 | +public class GuavaThreadPoolTest { |
| 20 | + |
| 21 | + @Test |
| 22 | + public void whenExecutingTaskWithDirectExecutor_thenTheTaskIsExecutedInTheCurrentThread() { |
| 23 | + |
| 24 | + Executor executor = MoreExecutors.directExecutor(); |
| 25 | + |
| 26 | + AtomicBoolean executed = new AtomicBoolean(); |
| 27 | + |
| 28 | + executor.execute(() -> { |
| 29 | + try { |
| 30 | + Thread.sleep(500); |
| 31 | + } catch (InterruptedException e) { |
| 32 | + e.printStackTrace(); |
| 33 | + } |
| 34 | + executed.set(true); |
| 35 | + }); |
| 36 | + |
| 37 | + assertTrue(executed.get()); |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + public void whenJoiningFuturesWithAllAsList_thenCombinedFutureCompletesAfterAllFuturesComplete() throws ExecutionException, InterruptedException { |
| 42 | + |
| 43 | + ExecutorService executorService = Executors.newCachedThreadPool(); |
| 44 | + ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService); |
| 45 | + |
| 46 | + ListenableFuture<String> future1 = listeningExecutorService.submit(() -> "Hello"); |
| 47 | + ListenableFuture<String> future2 = listeningExecutorService.submit(() -> "World"); |
| 48 | + |
| 49 | + String greeting = Futures.allAsList(future1, future2).get() |
| 50 | + .stream() |
| 51 | + .collect(Collectors.joining(" ")); |
| 52 | + assertEquals("Hello World", greeting); |
| 53 | + |
| 54 | + } |
| 55 | + |
| 56 | +} |
0 commit comments