File tree Expand file tree Collapse file tree
core-java-8/src/test/java/com/baeldung/completablefuture Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11package 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 .*;
94import java .util .stream .Collectors ;
105import java .util .stream .Stream ;
116
7+ import org .junit .Test ;
8+
129import static org .junit .Assert .assertEquals ;
1310import 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
You can’t perform that action at this time.
0 commit comments