Added cancellation example for CompletableFuture (#614)
This commit is contained in:
parent
e4f2bed4fd
commit
fe16518c17
@ -1,14 +1,11 @@
|
|||||||
package com.baeldung.completablefuture;
|
package com.baeldung.completablefuture;
|
||||||
|
|
||||||
import org.junit.Test;
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
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.Collectors;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
@ -46,6 +43,28 @@ public class CompletableFutureTest {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public 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
|
@Test
|
||||||
public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException {
|
public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException {
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user