Saturday, September 24, 2011

Throw an exception from a Java thread and handle it on the parent thread

Let say you want to compute a result in the background of a program. Usually it's achieved by encapsulate the task inside a Runnable object and run it in a new thread. If an error occurs during the process you want your program to be notified and handle errors. But unfortunately the run() method of the Runnable interface doesn't allow to throw exceptions.

In this post I will demonstrate a way to achieved that based on Callable and Executors.




The Callable Interface is very similar to Runnable, here is an implementation example :

To run this Callable task we need a Executors. The submit() method of the Executor take a Callable and return a Future which represents the result of the task. Finally we can call the get() method of Future to get the value of the result. If the call() method has thrown an exception get() will throw an ExecutionException which contains the original exception.
Here is an example :

1 comment:

  1. In that case main thread never done all task before created thread execution finished.

    ReplyDelete