Reputation: 1016
I have one main thread it has created many workers, every worker is a thread.
How can I get errors from the workers in main thread if there was an Exception in some worker or worker cannot successfully ended ?
How to send error before the worker thread dead ?
Upvotes: 7
Views: 2905
Reputation: 38910
Use ExecutorService or ThreadPoolExecutor
You can catch Exceptions in three ways
run() or call()
method in try{}catch{}Exceptoion{}
blocksafterExecute
method of ThreadPoolExecutor Refer to below SE question for more details:
Handling Exceptions for ThreadPoolExecutor
Upvotes: 1
Reputation: 7804
One way to achieve this is using signal passing in threads. Signal passing is used extensively, when you need threads to communicate between each other. Simple way to achieve this could be to access shared objects between threads and monitor the value of the object(indication of a signal).
You can assign some value to the object indicating failure(in form of a signal) so that other threads can take appropriate actions.
Using signals, you can not only passing failure signals but various other status signals as well by setting appropriate value to a shared object (say Enum with different values indicating state of the thread).
Refer this link for more details :http://tutorials.jenkov.com/java-concurrency/thread-signaling.html
Upvotes: 0
Reputation: 272217
If you use the java.util.concurrent Executor frameworks and generate a Future from each submitted worker, then calling get() on the Future will either give you the worker's result, or the exception thrown/caught within that worker.
Upvotes: 4
Reputation: 135992
You can set global UncaughtExceptionHandler which will intercept all uncaught Exceptions in all threads
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
...
}
});
Upvotes: 2