Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java multithreading errors handling

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 ?

like image 993
prilia Avatar asked Aug 14 '13 06:08

prilia


People also ask

How do you handle exceptions in multithreading in Java?

Uncaught exception handler will be used to demonstrate the use of exception with thread. It is a specific interface provided by Java to handle exception in the thread run method. There are two methods to create a thread: Extend the thread Class (java.

How do you handle exception in multithreaded environment?

We simply placed a try/catch block around the start() method. After all, start() instantiates the secondary thread and calls its run() method and the use of try/catch is the natural way of dealing with exceptions. If the code in run() throws any exceptions we should be able to catch them.

How are errors handled in Java?

The try-catch is the simplest method of handling exceptions. Put the code you want to run in the try block, and any Java exceptions that the code throws are caught by one or more catch blocks. This method will catch any type of Java exceptions that get thrown. This is the simplest mechanism for handling exceptions.

How do you handle exception thrown in thread?

Exception handling in Thread : By default run() method doesn't throw any exception, so all checked exceptions inside the run method has to be caught and handled there only and for runtime exceptions we can use UncaughtExceptionHandler.


3 Answers

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.

like image 92
Brian Agnew Avatar answered Oct 22 '22 03:10

Brian Agnew


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) {
        ...
    }
});
like image 32
Evgeniy Dorofeev Avatar answered Oct 22 '22 01:10

Evgeniy Dorofeev


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

like image 1
Ravindra babu Avatar answered Oct 22 '22 03:10

Ravindra babu