Domanda

I have two Callable tasks running at the same time, launched from a main thread. Either of these two Callables can throw an error and I need this error to be passed back to the main thread and handled there. Furthermore, as soon as the error occurs in either Callable, I would like to catch it in main. I can't see how this can be done, however. If I simply wait on the two Futures for the Callables

try {
    future1.get();
    future2.get();
} catch (ExecutionException e) {
    // Handle the error...
}

then I cannot catch the error as it occurs in the second callable. I'll have to wait until the first callable is done, either normally or it itself throws an error.

I cannot see how else I can achieve this. Are there any solutions to this?

È stato utile?

Soluzione

Use ExecutorCompletionService. It will queue up the most recently finished callable which in this case would be the first to throw an error.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top