It seems like I should be able to tell Futures apart from each other without having to maintain two HashMaps (or one bidirectional hash).
Am I missing something here, or is that the expected approach? I'd like to override Future to include a 'getId' method or something, but that doesn't seem feasible based on how the executor creates them.
Edit: I'm also trying to use ExecutorCompletionService to wait for jobs to be completed.
Never use java.util.concurrent.Future
. Use com.google.common.util.concurrent.ListenableFuture
or similar instead.
With ListenableFuture
s you can register callbacks when a ListenableFuture
completes:
ListenableFuture<Integer> future = MoreExecutors.listeningDecorator(executor).submit(
new Callable<Integer>() {
@Override
public Integer call() throws Exception {
...
}
});
// Add jobId to the map. You should use a thread-safe Map!
map.put(jobId, future);
Futures.addCallback(future, new FutureCallback<Integer>(){
@Override
public void onSuccess(Integer result) {
map.remove(jobId);
...
}
@Override
public void onFailure(Throwable t) {
map.remove(jobId);
...
}});