我想同时对两个不同的服务进行web调用.最后,我将2Response个对象压缩成一个流.我用的是Callable,但我不确定我用的是正确的方式.好像我还是会被Future的第一个get()电话挡住,对吧?有人能告诉我我走对了吗?这就是我目前的情况:

// submit the 2 calls to the thread pool
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
Future<Mono<Response<ProcessInstance>>> processFuture =
        executorService.submit(() -> getProcessInstances(processDefinitionKey, encryptedIacToken));
Future<Mono<Response<Task>>> taskFuture =
        executorService.submit(() -> getTaskResponses(processDefinitionKey, encryptedIacToken, 100, 0));

// get the result of the 2 calls
Optional<Tuple2<Response<ProcessInstance>, Response<Task>>> tuple;
try {
    Mono<Response<ProcessInstance>> processInstances = processFuture.get();
    Mono<Response<Task>> userTasks = taskFuture.get();
    tuple = processInstances.zipWith(userTasks).blockOptional();
} catch (InterruptedException e) {
    log.error("Exception while processing response", e);
    // Restore interrupted state...
    Thread.currentThread().interrupt();
    return emptyProcessResponseList;
} catch (ExecutionException e) {
    log.error("Exception while processing response", e);
    return emptyProcessResponseList;
}

推荐答案

给定:你需要等待两项任务完成.

如果processFuture先结束,你会立即失败,直到taskFuture结束.如果taskFuture先结束,你将阻塞到processFuture结束,但taskFuture.get()调用将在任务完成后立即返回.无论哪种情况,结果都是一样的.

你可以用CompletableFuture来代替,然后用CompletableFuture.allOf()来代替,但是对于这个简单的东西,你所拥有的很好用.另见第Waiting on a list of Future

Java相关问答推荐

PDFBox SmallMap不尊重Map.入口哈希码合同

如何在多个设备上同时运行Android Studio的项目?

@ EnableRouting注释在Kotlin项目中不工作

找到允许的最大底片

如何在SystemiccationRetryListenerSupport中获得类级别的spring retryable annotation中指定的标签?

路径映射未发生

为什么我要创建一个单独的互斥体/锁对象?

将不受支持的时区UT重写为UTC是否节省?

Hibernate EmptyInterceptor可以工作,但不能拦截器

Bean定义不是从Spring ApplationConext.xml文件加载的

解释左移在Java中的工作原理

Arrays.hashcode(int[])为不同的元素提供相同的散列

%This内置函数示例

来自外部模块的方面(对于Java+Gradle项目)不起作用

错误:不兼容的类型:Double不能转换为Float

Java集合:NPE,即使没有添加空值

如何制作回文程序?

JavaFX:为什么我的ComboBox添加了一个不必要的单元格的一部分?

如何使用带有可选参数的类生成器?

javax.crypto-密码对象-提供者服务是如何工作的?