7

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 ?

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
prilia
  • 996
  • 5
  • 18
  • 41
  • 3
    You should take a look at [`Callable`](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html) and [`Future`](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html). You could also use [`UncaughtExceptionHandler`](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.UncaughtExceptionHandler.html), although, I'd consider that a little dirty...You could also establish your own callback mechanism – MadProgrammer Aug 14 '13 at 06:59
  • Have a look at http://stackoverflow.com/questions/2248131/handling-exceptions-from-java-executorservice-tasks?rq=1 – Olga Aug 14 '13 at 07:05
  • Do you know about futurecallback interface ? http://stackoverflow.com/questions/18227173/java-multithreaded-programming-using-with-guava-futurecallback-interface ? – prilia Aug 14 '13 at 08:53

4 Answers4

4

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.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
2

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) {
        ...
    }
});
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

Use ExecutorService or ThreadPoolExecutor

You can catch Exceptions in three ways

  1. Future.get()
  2. Wrap entire run() or call() method in try{}catch{}Exceptoion{} blocks
  3. Override afterExecute method of ThreadPoolExecutor

Refer to below SE question for more details:

Handling Exceptions for ThreadPoolExecutor

Community
  • 1
  • 1
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
0

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

Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38