ThreadPoolExecutor、Futures:关联请求和响应

ThreadPoolExecutor, Futures: correlating requests and responses

我正在尝试使用包含所有项目的 ThreadPoolExecutor along with Future (results) and Callable (task to be executed), but I can't figure out a simple way of correlating input (Callable) with the corresponding result (Future), it seems the only sensible way would be to create a wrapper (example),但这对于如此简单的任务来说可能开销太大。

我错了吗?有任何建议的替代方案吗?

更好的方法是使用 invokeAll() 方法而不是 submit()。您需要向它提供 Callable 的集合,它将 return 与您的任务相同的顺序排列 Futures 的集合。此外,invokeAll() 允许您定义超时,因此您不需要锁存器。它将是这样的:

List<Callable> jobs = new ArrayList<>(requests.size());
for (String request : requests) {
    jobs.add(new MyCallable(request));
}
List<Future<ProcessedResponse>> futures = executor.invokeAll(jobs, timeout, TimeUnit.MILLISECONDS);
Iterator<String> it = requests.iterator();
for (Future<ProcessedResponse> future: futures) {
    String request = it.next();  // This request corresponds to this future
    if (future.isDone()) {
        results.add(new Result(request, future.get()));
    } else {
        future.cancel(true);
    }
}