Question

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.

Was it helpful?

Solution

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 the ExecutionException (if any).

Note that calling get in 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 wrapped Runnable will be caught byFutureTask.run()`.)

OTHER TIPS

Check Thread.UncaughtExceptionHandler

I think you should use 'setException' to report the failure from your task. It will make get() report an ExecutionException. See this as well:

How to catch exceptions in FutureTask

A CompletionService might be a possibility here. Using one of those will allow you to call get() on the Futures once they are definitely finished. Alternatively, the Guava libraries have ways to add a listener to a Future or FutureTask to execute when the task is complete (the ListenableFuture and its related objects).

You can also check an example I wrote for Futuretask

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top