I’ve got an application which regularly submits tasks to be executed in a dedicated thread. Those tasks are FutureTask<V> and the thread is no more than an infinite loop which executes the jobs as they get into a queue, going to sleep if empty.
Sometimes I need to wait for the result of a computation, so I call FutureTask’s get() method, which will also throw an exception if something bad happened. But there are cases where I don’t care what the result was, if any, but I need to know (log, printStackTrace() or whatever…) if there was some kind of failure during the task execution.
Is there any way I could achieve this without having to wait on a get() that I don’t need?
Thanks in advance!
UPDATE: Calling get() on the runner thread after executing the task seemed to be the only way to catch the exception if no one else would wait for the result.
Another solution would be extending FutureTask class to provide a method which, via java reflection, exposes sync.exception private field.
If I understand your problem correctly, there is a simple solution. Modify your dedicated task-runner thread to call
Future.get()after running each task, and catch and log theExecutionException(if any).Note that calling
getin the task-runner thread after running the task is guaranteed not to block.(Uncaught exception handlers won’t help because any exception and error thrown by the
run()method of the future’s wrappedRunnable will be caught byFutureTask.run()`.)