简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM