The following editor will bring you an article based on exception handling methods in Java sub-threads (general). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
In an ordinary single-threaded program, catching exceptions only requires try...catch...finally...code blocks. So, in a concurrent situation, for example, if a child thread is started in the parent thread, how to catch the exception from the child thread in the parent thread and handle it accordingly?
Common mistakes
Some people may think that it is very simple, just try...catch directly where the parent thread starts the child thread. Just do it, but actually this is wrong.
Cause analysis
Let us recall the complete signature of the run method of the Runnable interface. Because the throws statement is not identified, the method will not Throws a checked exception. As for unchecked exceptions such as RuntimeException, since the new thread is scheduled and executed by the JVM, if an exception occurs, the parent thread will not be notified.
public abstract void run()
Solution
So, how to capture the data from the child thread in the parent thread What about exceptions? The author thought of 3 common methods and shared them with everyone.
Method 1: try...catch...
The simplest and most effective way is to use the sub-thread method , wrap the places where exceptions may occur with try...catch... statements. Sub-thread code:
public class ChildThread implements Runnable { public void run() { doSomething1(); try { // 可能发生异常的方法 exceptionMethod(); } catch (Exception e) { // 处理异常 System.out.println(String.format("handle exception in child thread. %s", e)); } doSomething2(); } }
Method 2: Set the exception handler UncaughtExceptionHandler
for the thread Set exception handler. The specific methods can be as follows:
(1) Thread.setUncaughtExceptionHandler sets the exception handler of the current thread
(2) Thread.setDefaultUncaughtExceptionHandler sets the default exception handler for the entire program. If the current If the thread has an exception handler (default is none), the UncaughtExceptionHandler class will be used first; otherwise, if the thread group to which the current thread belongs has an exception handler, the thread group's ExceptionHandler will be used; otherwise, the global default DefaultUncaughtExceptionHandler will be used; if there is none , the child thread will exit.
Note: An exception occurs in the child thread. If there is no class to take over the processing, it will exit directly without leaving any logs. Therefore, if you do nothing, there will be a "weird" phenomenon in which the sub-thread task is not executed and there is no log prompt.
Set the exception handler for the current thread:
public class ChildThread implements Runnable { private static ChildThreadExceptionHandler exceptionHandler; static { exceptionHandler = new ChildThreadExceptionHandler(); } public void run() { Thread.currentThread().setUncaughtExceptionHandler(exceptionHandler); System.out.println("do something 1"); exceptionMethod(); System.out.println("do something 2"); } public static class ChildThreadExceptionHandler implements Thread.UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable e) { System.out.println(String.format("handle exception in child thread. %s", e)); } } }
Or, set the default exception handler for all threads
public class ChildThread implements Runnable { private static ChildThreadExceptionHandler exceptionHandler; static { exceptionHandler = new ChildThreadExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(exceptionHandler); } public void run() { System.out.println("do something 1"); exceptionMethod(); System.out.println("do something 2"); } private void exceptionMethod() { throw new RuntimeException("ChildThread exception"); } public static class ChildThreadExceptionHandler implements Thread.UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable e) { System.out.println(String.format("handle exception in child thread. %s", e)); } } }
Command line output: do something 1
handle exception in child thread. java.lang.RuntimeException: ChildThread exception
Method three, through Future The get method catches the exception
Use the thread pool to submit a method that can obtain the return information, that is, ExecutorService.submit(Callable) can obtain a Future object of the thread execution result after submitting. , and if an exception occurs in the child thread, when obtaining the return value through future.get(), the ExecutionException exception can be caught, thereby knowing that an exception has occurred in the child thread.
Child thread code:
public class ChildThread implements Callable { public Object call() throws Exception { System.out.println("do something 1"); exceptionMethod(); System.out.println("do something 2"); return null; } private void exceptionMethod() { throw new RuntimeException("ChildThread1 exception"); } }
Parent thread code:
public class Main { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(8); Future future = executorService.submit(new ChildThread()); try { future.get(); } catch (InterruptedException e) { System.out.println(String.format("handle exception in child thread. %s", e)); } catch (ExecutionException e) { System.out.println(String.format("handle exception in child thread. %s", e)); } finally { if (executorService != null) { executorService.shutdown(); } } } }
Command line output: do something 1
handle exception in child thread. java.util.concurrent.ExecutionException: java.lang.RuntimeException: ChildThread1 exception
##Summary
The above are 3 commonly used Java sub-thread exception handling methods. In fact, the author also thought of several other solutions in specific scenarios. I will analyze them another day. Thank you for your support~The above is the detailed content of Introduction to the general method of exception handling in Java sub-threads. For more information, please follow other related articles on the PHP Chinese website!