标签: completion-stage

如何使用 CompletionStage 的集合很好地执行 allOf/AnyOf

目前要使用 CompletionStage 的集合做一些简单的事情需要跳过几个难看的圈子:

public static CompletionStage<String> translate(String foo) {
    // just example code to reproduce
    return CompletableFuture.completedFuture("translated " + foo);
}

public static CompletionStage<List<String>> translateAllAsync(List<String> input) {
    List<CompletableFuture<String>> tFutures = input.stream()
        .map(s -> translate(s)
            .toCompletableFuture())
        .collect(Collectors.toList()); // cannot use toArray because of generics Arrays creation :-(
    return CompletableFuture.allOf(tFutures.toArray(new CompletableFuture<?>[0])) // not using size() on purpose, see comments
        .thenApply(nil -> tFutures.stream()
            .map(f -> f.join())
            .map(s -> s.toUpperCase())
            .collect(Collectors.toList()));
}
Run Code Online (Sandbox Code Playgroud)

我想写的是:

public CompletionStage<List<String>> translateAllAsync(List<String> input) {
    // allOf takes a collection< futures<X>>, …
Run Code Online (Sandbox Code Playgroud)

java-8 completion-stage

5
推荐指数
1
解决办法
797
查看次数

如何强制 CompletableFuture.thenApply() 在运行前一阶段的同一线程上运行?

这是我面临的问题的简短代码版本:

public static void main(String[] args) {
    CompletableFuture.supplyAsync(() -> {
                /*
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ignored) {}
                */
                //System.out.println("supplyAsync: " + Thread.currentThread().getName());
                return 1;
            })
            .thenApply(i -> {
                System.out.println("apply: " + Thread.currentThread().getName());
                return i + 1;
            })
            .thenAccept((i) -> {
                System.out.println("accept: " + Thread.currentThread().getName());
                System.out.println("result: " + i);
            }).join();
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出:

apply: main
accept: main
result: 2
Run Code Online (Sandbox Code Playgroud)

看到main那里我很惊讶!Thread.sleep()我预计当我取消注释该调用或什至取消注释单个语句时会发生类似的情况sysout

supplyAsync: ForkJoinPool.commonPool-worker-1
apply: ForkJoinPool.commonPool-worker-1
accept: ForkJoinPool.commonPool-worker-1
result: 2
Run Code Online (Sandbox Code Playgroud)

我理解thenApplyAsync()将确保它不会在main线程上运行,但我想避免将供应商从运行的线程返回的数据传递supplyAsync …

java multithreading asynchronous completable-future completion-stage

4
推荐指数
1
解决办法
2920
查看次数

使用 CompletionStage 而不是 CompletableFuture

给出以下方法:

private static String getChuckNorrisJoke () {
    try {
        HttpURLConnection con = (HttpURLConnection) new
        URL( "http://api.icndb.com/jokes/random" ).openConnection();
        BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null ) {
            response.append(line);
        }
        in.close();
        return response.toString();
    } catch (IOException e) {
        throw new IllegalStateException( "Something is wrong: " , e);
    }
}
Run Code Online (Sandbox Code Playgroud)

以下语句可用于以异步方式运行该方法。

final CompletableFuture<String> jokeAsync = CompletableFuture.supplyAsync(() -> getChuckNorrisJoke());
Run Code Online (Sandbox Code Playgroud)

尽管我认为我理解CompletionStage与 的关系CompletableFuture,但我不确定如何使用它CompletionStage来完成相同的任务。

final CompletionStage<String> jokeAsync = …
Run Code Online (Sandbox Code Playgroud)

java lambda completable-future completion-stage

2
推荐指数
1
解决办法
4410
查看次数

为什么当有一个尚未完成的完成阶段时主线程不终止?

这是我的简单代码:

public class Main4 {
    public static void main(String[] args) {
        System.out.println("Hello from thread: "+Thread.currentThread().getName());
        new Game().run();
        System.out.println("I am dying ... ");
    }

    static class Game {
        public void run() {
            value();
        }

        private int value() {
            int number = 0;
            CompletionStage<Void> c = calculate().thenApply(i -> i + 3).thenAccept(i -> System.out.println("I am done, and my value is " + i));
            return number;
        }

        private CompletionStage<Integer> calculate() {
            CompletionStage<Integer> completionStage = new CompletableFuture<>();
            Executors.newCachedThreadPool().submit(() -> {
                System.out.println("I am in the thread: …
Run Code Online (Sandbox Code Playgroud)

java multithreading threadpool completable-future completion-stage

1
推荐指数
1
解决办法
2320
查看次数

CompleteExceptionally 和 obtrudeException 之间的区别

只是浏览CompletableFuture文档并偶然发现了completeExceptionallyobtrudeException方法,并且很难理解差异和用例。社区可以通过示例帮助理解差异和用例吗?

java multithreading asynchronous completable-future completion-stage

1
推荐指数
1
解决办法
3935
查看次数