'Java CompletableFuture not cancelling underlying execution

I am expecting that from the below code, due to timeouts the completablefutures will stop processing. But I can see that that cancel has no effect.

public class CompletableFutureTest {

    public static void main(final String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(10);
        CompletableFuture completableFuture;
        CompletableFuture completableFuture2;
        completableFuture =
                CompletableFuture.runAsync(() -> callSomeMethod(1), executor);
        completableFuture2 =
                CompletableFuture.runAsync(() -> callSomeMethod(2), executor);
        try {

            System.out.println("After everything");
            completableFuture.get(2, TimeUnit.SECONDS);
            completableFuture2.get(2, TimeUnit.SECONDS);
        } catch (ExecutionException e) {
            cancelCompletableFuture(completableFuture);
            cancelCompletableFuture(completableFuture2);
        }  catch (TimeoutException e) {
            cancelCompletableFuture(completableFuture);
            cancelCompletableFuture(completableFuture2);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

    }

    private static void callSomeMethod(int i) {
        System.out.println("In some method" + i);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted");
        }
        System.out.println("After sleep" + i);
    }

    private static void cancelCompletableFuture(CompletableFuture completableFuture) {
        completableFuture.cancel(true);
    }


}

I can see the 2 completable futures still running.



Solution 1:[1]

The javadoc for CompletableFuture has the answer to your question, specifically the comment for the mayInterruptIfRunning parameter of the cancel method:

mayInterruptIfRunning – this value has no effect in this implementation because interrupts are not used to control processing.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 flwd