How to cancel Java 8 completable future?

前端 未结 5 1823
面向向阳花
面向向阳花 2020-12-09 16:28

I am playing with Java 8 completable futures. I have the following code:

CountDownLatch waitLatch = new CountDownLatch(1);

CompletableFuture future         


        
5条回答
  •  感情败类
    2020-12-09 16:32

    Apparently, it's intentional. The Javadoc for the method CompletableFuture::cancel states:

    [Parameters:] mayInterruptIfRunning - this value has no effect in this implementation because interrupts are not used to control processing.

    Interestingly, the method ForkJoinTask::cancel uses almost the same wording for the parameter mayInterruptIfRunning.

    I have a guess on this issue:

    • interruption is intended to be used with blocking operations, like sleep, wait or I/O operations,
    • but neither CompletableFuture nor ForkJoinTask are intended to be used with blocking operations.

    Instead of blocking, a CompletableFuture should create a new CompletionStage, and cpu-bound tasks are a prerequisite for the fork-join model. So, using interruption with either of them would defeat their purpose. And on the other hand, it might increase complexity, that's not required if used as intended.

提交回复
热议问题