Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to notice an exception from the parent thread?

I'm feeding threads into an ExecutorService.

These threads are manipulating some data, and if there's a conflict, the data object throws an exception, which is caught by the conflicting thread, which in turn aborts and does not complete execution.

When this happens, the aborting thread needs to be put back in the queue and fed back into the executor.

How can I tell if an exception was thrown, from the parent thread?

like image 494
temporary_user_name Avatar asked Dec 10 '12 07:12

temporary_user_name


People also ask

How do you catch an exception in a thread?

Exceptions are caught by handlers(here catch block). Exceptions are caught by handlers positioned along with the thread's method invocation stack. If the calling method is not prepared to catch the exception, it throws the exception up to its calling method and so on.

What happens if a child thread throws exception?

Short answer, it doesn't. If the exception propagates all the way out of the thread, it'll simply die (possible generating some error print on the console).

What happens if there is exception in thread?

An exception is an issue (run time error) occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.

Does child thread see the value of parent thread local?

By default, child thread value is exactly the same as parent thread value.


1 Answers

When you submit() a task on the ExecutorService you get a Future as a result. When the execution has finished you can call get() on that future. This will return the result if applicable, or it will throw an ExecutionException if the original task threw one. If you want the real exception object you can do getCause().

Also note that you would be putting a Task back into the service, that task is ran on a Thread which has not really terminated (just caught the exception and is waiting for a new one).

Here is an example usage (you can use Runnable if you don't care for the result).

Callable<String> myCallable = ...;
Future<String> future = myExector.submit(myCallable);

// Do something else until myCallable.isDone() returns true.
try {
    String result = future.get();
}catch(ExecutionException e){
    // Handle error, perhaps create new Callable to submit.
}
like image 101
Thirler Avatar answered Oct 26 '22 09:10

Thirler