- Exception handling in Java child threads
- Reason analysis
- Solutions
- Method 1: try . catch in child thread
- Method 2: set the exception handler UncaughtExceptionHandler for the thread
- Method 3: catch the exception through the get method of Future
- Hot Categories
- Hot Tags
- Java Threads
- What are the ways to create a thread in java program?
- How to create a thread using Runnable interface?
- How to create a thread using Thread class?
- How to create a multiple threads in java program?
Exception handling in Java child threads
In usual single threaded program, catching exceptions only needs to be done through «try . catch . finally . » code block. Then, in the concurrent case, such as starting child threads in the parent thread, how to catch the exception from the child threads in the parent thread and handle it accordingly?
Some people might think that it’s simple, in the place of parent thread to start the child thread, directly try. catch, but in fact, this is wrong.
Reason analysis
Let’s recall the full signature of the run method of the Runnable interface, because it does not identify the throws statement, so the method does not throw the checked exception. As for RuntimeException, because new threads are scheduled and executed by JVM, the parent thread is not notified if an exception occurs.
Solutions
So, how to catch an exception from a child thread in the parent thread? Here to share you 3 commonly used methods.
Method 1: try . catch in child thread
The simplest and most effective way is in the child thread method, the place where the exception may occur, with try. catch. statement wrapped up.
1 public class ChildThread implements Runnable 2 public void run() 3 doSomething1(); 4 try 5 // A method that might cause an exception 6 exceptionMethod(); 7 > catch (Exception e) 8 // Handle exception 9 System.out.println(String.format("handle exception in child thread. %s", e)); 10 > 11 doSomething2(); 12 > 13 >
Method 2: set the exception handler UncaughtExceptionHandler for the thread
Setting an exception handler for the thread. Specific practices can be as follows:
(1) Thread.setUncaughtExceptionHandler set the exception handler for the current thread
(2) Thread.setDefaultUncaughtExceptionHandler set the default exception handler for the entire program
If the current thread has an exception handler(none by default), the UncaughtExceptionHandler class is used preferentially; otherwise, if the thread group of the current thread has an exception handler, then the thread group's ExceptionHandler is used; otherwise, the global default DefaultUncaughtExceptionHandler is used; if none, the child thread will exit.
Note: an exception has occurred in the child thread. If no class has taken over the process, it will exit without leaving any logs printed.
So, if do nothing, there will be a weird phenomenon in which the child thread task has not been executed, and there is no log hint.
Sets the exception handler for the current thread:
1 public class ChildThread implements Runnable 2 private static ChildThreadExceptionHandler exceptionHandler; 3 4 static 5 exceptionHandler = new ChildThreadExceptionHandler(); 6 > 7 8 public void run() 9 Thread.currentThread().setUncaughtExceptionHandler(exceptionHandler); 10 System.out.println("do something 1"); 11 exceptionMethod(); 12 System.out.println("do something 2"); 13 > 14 15 public static class ChildThreadExceptionHandler implements Thread.UncaughtExceptionHandler 16 public void uncaughtException(Thread t, Throwable e) 17 System.out.println(String.format("handle exception in child thread. %s", e)); 18 > 19 > 20 >
Or, set the default exception handler for all threads
1 public class ChildThread implements Runnable 2 private static ChildThreadExceptionHandler exceptionHandler; 3 4 static 5 exceptionHandler = new ChildThreadExceptionHandler(); 6 Thread.setDefaultUncaughtExceptionHandler(exceptionHandler); 7 > 8 9 public void run() 10 System.out.println("do something 1"); 11 exceptionMethod(); 12 System.out.println("do something 2"); 13 > 14 15 private void exceptionMethod() 16 throw new RuntimeException("ChildThread exception"); 17 > 18 19 public static class ChildThreadExceptionHandler implements Thread.UncaughtExceptionHandler 20 public void uncaughtException(Thread t, Throwable e) 21 System.out.println(String.format("handle exception in child thread. %s", e)); 22 > 23 > 24 >
do something 1 handle exception in child thread. java.lang.RuntimeException: ChildThread exception
Method 3: catch the exception through the get method of Future
Use the thread pool to submit a method that can get the return information, that is, ExecutorService.submit(Callable)
After submit, you can get the Future object of a thread execution result, and if an exception occurs in the child thread, when getting the return value by future.get(), we can catch ExecutionException as well, so that we know an exception occurs in the child thread.
1 public class ChildThread implements Callable 2 public Object call() throws Exception 3 System.out.println("do something 1"); 4 exceptionMethod(); 5 System.out.println("do something 2"); 6 return null; 7 > 8 9 private void exceptionMethod() 10 throw new RuntimeException("ChildThread1 exception"); 11 > 12 >
1 public class Main 2 public static void main(String[] args) 3 ExecutorService executorService = Executors.newFixedThreadPool(8); 4 Future future = executorService.submit(new ChildThread()); 5 try 6 future.get(); 7 > catch (InterruptedException e) 8 System.out.println(String.format("handle exception in child thread. %s", e)); 9 > catch (ExecutionException e) 10 System.out.println(String.format("handle exception in child thread. %s", e)); 11 > finally 12 if (executorService != null) 13 executorService.shutdown(); 14 > 15 > 16 > 17 >
do something 1 handle exception in child thread. java.util.concurrent.ExecutionException: java.lang.RuntimeException: ChildThread1 exception
Posted by luckppp in Java at Sep 25, 2017 — 6:00 PM
Hot Categories
Hot Tags
- Java × 8678
- Python × 3398
- Algorithm × 2157
- Linux × 2069
- Javascript × 1932
- data structure × 1524
- Spring × 1497
- C++ × 1439
- MySQL × 1163
- Database × 1138
- Front-end × 1057
- Design Pattern × 1024
Java Threads
What are the ways to create a thread in java program?
How to create a thread using Runnable interface?
// Create a thread by implementing Runnable interface in java program class ChildThread implements Runnable < Thread thr; ChildThread() < thr = new Thread(this, "Child Thread Task"); System.out.println("Child thread: " + thr); //starts child thread here thr.start(); >public void run() < try < int i = 0; while( i > catch(InterruptedException ex) < System.out.println("Child thread is interrupted."); >System.out.println("Child thread is completed"); > > class ThreadTest < public static void main(String args[]) < // Creates the child thread new ChildThread(); try < int i = 0; while( i > catch(InterruptedException ex) < System.out.println("Main thread is interrupted."); >System.out.println("Main thread is completed"); > >
$ javac ThreadTest.java $ java ThreadTest Child thread: Thread[Child Thread Task,5,main] Main thread i: 0 Child thread i: 0 Child thread i: 1 Main thread i: 1 Child thread i: 2 Main thread i: 2 Child thread i: 3 Child thread i: 4 Main thread i: 3 Child thread is completed Main thread i: 4 Main thread is completed
How to create a thread using Thread class?
// Create a thread by extending Thread class in java program class ChildThread extends Thread < ChildThread() < super("Child Thread Task"); System.out.println("Child thread: " + this); //starts child thread here start(); >public void run() < try < int i = 0; while( i > catch(InterruptedException ex) < System.out.println("Child thread is interrupted."); >System.out.println("Child thread is completed"); > > class ExtendThreadTest < public static void main(String args[]) < // Creates the child thread new ChildThread(); try < int i = 0; while( i > catch(InterruptedException ex) < System.out.println("Main thread is interrupted."); >System.out.println("Main thread is completed"); > >
Child thread: Thread[Child Thread Task,5,main] Main thread i: 0 Child thread i: 0 Child thread i: 1 Main thread i: 1 Child thread i: 2 Main thread i: 2 Child thread i: 3 Child thread i: 4 Main thread i: 3 Child thread is completed Main thread i: 4 Main thread is completed
How to create a multiple threads in java program?
// Multiple Threads creation in java program class ChildThread implements Runnable < Thread thr; String threadName; ChildThread(String name) < threadName = name; thr = new Thread(this, threadName); System.out.println(threadName + "- Child thread: " + thr); //starts child thread here thr.start(); >public void run() < try < int i = 0; while( i > catch(InterruptedException ex) < System.out.println(threadName + "- Child thread is interrupted."); >System.out.println(threadName + "- Child thread is completed"); > > class MultipleThreadTest < public static void main(String args[]) < // Creates the child thread new ChildThread("one"); new ChildThread("two"); try < int i = 0; while( i > catch(InterruptedException ex) < System.out.println("Main thread is interrupted."); >System.out.println("Main thread is completed"); > >
$ javac MultipleThreadTest.java $ java MultipleThreadTest one- Child thread: Thread[one,5,main] two- Child thread: Thread[two,5,main] one- Child thread i: 0 Main thread i: 0 two- Child thread i: 0 one- Child thread i: 1 two- Child thread i: 1 Main thread i: 1 one- Child thread i: 2 two- Child thread i: 2 Main thread i: 2 one- Child thread i: 3 two- Child thread i: 3 one- Child thread i: 4 two- Child thread i: 4 Main thread i: 3 one- Child thread is completed two- Child thread is completed Main thread i: 4 Main thread is completed