vavr-io/vavr

Chained futures keep executing although future was cancelled

Closed

#2552 opened on Jan 10, 2020

View on GitHub
 (12 comments) (0 reactions) (0 assignees)Java (5,390 stars) (605 forks)batch import
bughelp wanted«vavr-concurrent»

Description

Further investigation of #2551 shows that CompletableFutures behave differently in a Spring application.

The following code using CompletableFutures stops before the thenRun method is executed:

CompletableFuture<Void> f = CompletableFuture.runAsync(() -> {
    for (int i = 0; i < 10; i++) {
        try {
            System.out.println(i);
            Thread.sleep(200);
        } catch (InterruptedException e) {
        }
    }
}).thenRun(() -> {
    for (int i = 0; i < 10; i++) {
        try {
            System.out.println(i);
            Thread.sleep(200);
        } catch (InterruptedException e) {
        }
    }
});
Thread.sleep(500);

f.cancel(true);
try{
    f.get();
}
catch(CancellationException | ExecutionException e){
    System.out.println("future cancelled");
}
System.out.println("end");

Output:

1
2
future cancelled
end
3
4
5
6
7
8
9

However, when using the vavr future implementation, the second part is executed as well:

Future<Void> f = Future.run(() -> {
    int i = 1;
    while(i < 10){
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
        }
        System.out.println(i++);
    }
}).andThen(v -> {
    int i = 1;
    while(i < 10){
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
        }
        System.out.println(i++);
    }
});
Thread.sleep(500);
f.cancel();
try{
    f.get();
}
catch(CancellationException e){
    System.out.println("future cancelled");
}

System.out.println("end");

Output:

1
2
future cancelled
end
3
4
5
6
7
8
9
1
2
3
4
5
6
7
8
9

Contributor guide