Java8 thenCompose和thenComposeAsync之间的区别

时间:2017-09-09 12:59:21

标签: java java-8 completable-future

鉴于这段代码:

.map(future -> future.thenCompose(quote ->
                CompletableFuture.supplyAsync(
                        () -> Discount.applyDiscount(quote), executor
                )))

这一部分:

.map(future -> 
    future.thenComposeAsync(quote -> Discount.applyDiscount(quote), executor))

可以改写为:

REST_FRAMEWORK = {
    ...
    'TEST_REQUEST_DEFAULT_FORMAT': 'json'
}

我从一本书的例子中得到了这个代码,并说两种解决方案不同,但我不明白为什么。

1 个答案:

答案 0 :(得分:0)

让我们考虑一个如下所示的函数:

public class Remove_DuplicateIN_String {

    public static void main(String a[]) throws IOException {
        String a1;//=new String[200];
        int i;
        InputStreamReader reader=new InputStreamReader(System.in);
        BufferedReader in =new BufferedReader(reader);
        System.out.println("Enter the String ");
            a1=(in.readLine());
            System.out.print(a1);
        System.out.println("\n");
        String words[]=new String[100];
        words=a1.split(" ");
        System.out.println(words.length);
        Set<String> uniq=new HashSet<String>();
        for(i=0;i<words.length;i++)
        {
            uniq.add(words[i]);
        }
        Iterator it=uniq.iterator();
        while(it.hasNext())
        {
            System.out.print(it.next()+" ");
        }
    }
}

区别在于调用哪个线程public CompletableFuture<String> requestData(String parameters) { Request request = generateRequest(parameters); return CompletableFuture.supplyAsync(() -> sendRequest(request)); }

generateRequest()将在与上游任务相同的线程上调用thenCompose(如果上游任务已经完成,则调用调用线程)。

如果提供的话,

generateRequest()会在提供的执行者上调用thenComposeAsync,否则会调用默认的generateRequest()