Continuations in Java

前端 未结 11 1971
再見小時候
再見小時候 2020-12-05 00:20

Is there a good implementation of continuations in Java?

If so, what is the overhead like? The JVM wasn\'t designed with these sort of things in mind, right? So is t

11条回答
  •  独厮守ぢ
    2020-12-05 01:08

    Since Java 8, there is now a CompletableFuture class which supports continuations and more functional / reactive programming approaches.

    Consider the following example, where a Class offers a downloadAndResize method:

    public CompletableFuture downloadAndResize(String imageUrl, int width, int height) {
        return CompletableFuture
            .supplyAsync(() -> downloadImage(imageUrl))
            .thenApplyAsync(x -> resizeImage(x, width, height));
    }
    
    private Image downloadImage(String url){
        // TODO Download the image from the given url...
    }
    
    private Image resizeImage(Image source, int width, int height){
        // TODO Resize the image to w / h
    }
    

    Usage of the above method could look like:

    CompletableFuture imagePromise = downloadAndResize("http://some/url", 300, 200);
    
    imagePromise.thenAccept(image -> {
        // Gets executed when the image task has successfully completed
    
        // do something with the image
    
    });
    

提交回复
热议问题