我在Spring boot应用程序中有一个用例,如下所示:
我想使用以下函数从响应中获取id字段值:
String id = getIdFromResponse(response);如果我在响应中没有获得任何id,那么我将使用以下函数检查请求参数中是否存在id字段:
String id = getIdFromRequest(request);到目前为止,我将按顺序调用它们。但是我想让这两个函数并行运行,一旦我从它们中的任何一个得到id,我就会停止。
我想知道是否有任何方法可以在Java8中使用streams来实现这一点。
发布于 2020-10-21 15:40:48
没有必要使用Stream API,只要有一个方法就可以做到这一点。
ExecutorService::invokeAny(Collection>)
执行给定的任务,返回已成功完成的任务的结果(即,没有抛出异常)。在正常或异常返回时,取消未完成的任务。
List<Callable<String>> collection = Arrays.asList(
() -> getIdFromResponse(response),
() -> getIdFromRequest(request)
);
// you want the same number of threads as the size of the collection
ExecutorService executorService = Executors.newFixedThreadPool(collection.size());
String id = executorService.invokeAny(collection);三个注意事项:
如果没有及时可用的结果,还有一个超时抛出TimeoutException的重载方法:invokeAny(Collection>, long, TimeUnit)
ExecutionException和InterruptedException完成后忘记关闭invokeAny https://stackoverflow.com/questions/64458149
复制相似问题