Skip to content

Commit fe16518

Browse files
forketyforkpivovarit
authored andcommitted
Added cancellation example for CompletableFuture (eugenp#614)
1 parent e4f2bed commit fe16518

1 file changed

Lines changed: 25 additions & 6 deletions

File tree

‎core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
11
package com.baeldung.completablefuture;
22

3-
import org.junit.Test;
4-
5-
import java.util.concurrent.CompletableFuture;
6-
import java.util.concurrent.ExecutionException;
7-
import java.util.concurrent.Executors;
8-
import java.util.concurrent.Future;
3+
import java.util.concurrent.*;
94
import java.util.stream.Collectors;
105
import java.util.stream.Stream;
116

7+
import org.junit.Test;
8+
129
import static org.junit.Assert.assertEquals;
1310
import static org.junit.Assert.assertTrue;
1411

@@ -46,6 +43,28 @@ public void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediate
4643

4744
}
4845

46+
47+
public Future<String> calculateAsyncWithCancellation() throws InterruptedException {
48+
CompletableFuture<String> completableFuture = new CompletableFuture<>();
49+
50+
Executors.newCachedThreadPool().submit(() -> {
51+
Thread.sleep(500);
52+
completableFuture.cancel(false);
53+
return null;
54+
});
55+
56+
return completableFuture;
57+
}
58+
59+
60+
@Test(expected = CancellationException.class)
61+
public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException {
62+
63+
Future<String> future = calculateAsyncWithCancellation();
64+
future.get();
65+
66+
}
67+
4968
@Test
5069
public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException {
5170

0 commit comments

Comments
 (0)