Gonzalo Vasquez Gonzalo Vasquez - 1 month ago 7
Java Question

ThreadPoolExecutor, Futures: correlating requests and responses

I'm trying to use a 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) that contains all items, but this might be too much overhead for such a simple task.

Am I wrong? Any suggested alternatives?


A better approach would be to use the invokeAll() method instead of submit(). You need to provide a collection of Callables to it and it will return a collection of Futures in the same sequential order as your tasks. Moreover, invokeAll() lets you define a timeout, so you don't need latches. It will be something like that:

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 {