Transform Java Future into a CompletableFuture

前端 未结 6 1276
野的像风
野的像风 2020-11-27 15:43

Java 8 introduces CompletableFuture, a new implementation of Future that is composable (includes a bunch of thenXxx methods). I\'d like to use this exclusively,

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 15:54

    If the library you want to use also offers a callback style method in addition to the Future style, you can provide it a handler that completes the CompletableFuture without any extra thread blocking. Like so:

        AsynchronousFileChannel open = AsynchronousFileChannel.open(Paths.get("/some/file"));
        // ... 
        CompletableFuture completableFuture = new CompletableFuture();
        open.read(buffer, position, null, new CompletionHandler() {
            @Override
            public void completed(Integer result, Void attachment) {
                completableFuture.complete(buffer);
            }
    
            @Override
            public void failed(Throwable exc, Void attachment) {
                completableFuture.completeExceptionally(exc);
            }
        });
        completableFuture.thenApply(...)
    

    Without the callback the only other way I see solving this is to use a polling loop that puts all your Future.isDone() checks on a single thread and then invoking complete whenever a Future is gettable.

提交回复
热议问题