JAVA Thread exception monitoring, javathread

Source: Internet
Author: User

JAVA Thread exception monitoring, javathread

 

I. Scenario Description: A single-threaded program can capture program exceptions using try... catch, while a multi-threaded program cannot be captured using try... catch.

Example 1: a multi-thread exception occurs. try... catch cannot be used to capture the problem.

public class NoCaughtThread  implements Runnable{    @Override    public void run() {        System.out.println(3 / 2);        System.out.println(3 / 0);        System.out.println(3 / 1);    }        public static void main(String[] args) {        try {            Thread thread = new Thread(new NoCaughtThread());            thread.start();        } catch (Exception e) {            System.out.println("==Exception: " + e.getMessage());        }    }}

Running result:

1
Exception in thread "Thread-0" java. lang. ArithmeticException:/by zero
At threadtest. NoCaughtThread. run (NoCaughtThread. java: 7)
At java. lang. Thread. run (Thread. java: 724)

Obviously, this is not an exception capture set by the program. At this time, try... catch cannot catch the exception of the thread. At this time, if the thread terminates the execution due to an exception, the exception cannot be detected. The reason is that the Thread-class run () method does not throw any check-type exception, but may be aborted due to an exception.

2. There are roughly two solutions: ① set the corresponding exception handling in run () and take the initiative to solve the undetected exception; ② provided in Thread APIsInterfaceThe UncaughtExceptionHandler API contains the uncaughtException method, which can detect the final state of an uncaptured exception;

Example 2: actively detect exceptions

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class InitiativeCaught {    public static void main(String[] args) {        InitialtiveThread initialtiveThread = new InitialtiveThread() ;        ExecutorService exec = Executors.newCachedThreadPool();        exec.execute(initialtiveThread);        exec.shutdown();    }}class InitialtiveThread implements Runnable {    @Override    public void run() {        Throwable thrown = null;        try {            System.out.println(3 / 2);            System.out.println(3 / 0);            System.out.println(3 / 1);        } catch (Throwable e) {            thrown = e;        } finally {            threadDeal(this, thrown);        }    }        public void threadDeal(Runnable r, Throwable t) {        System.out.println("==Exception: " + t.getMessage());    }  }

Running result:

1
= Exception:/by zero

In this case, the exception is caught and processed to obtain the desired result.

 

Example 3: The UncaughtExceptionHandler interface is provided in the Thread-class API to capture exceptions. It is required to detect Thread exceptions. If an exception occurs, it is set to end the Thread three times after repeated calls.

Import java. lang. thread. uncaughtExceptionHandler; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class ThreadMonitor implements Runnable {private int data; // you can set the parameter private int control = 0 by constructing the parameter; private static final int MAX = 3; // set the number of retries public ThreadMonitor (int I) {this. data = I;} public ThreadMonitor () {// TODO Auto-generated constructor stub} @ Overri De public void run () {Thread. setDefaultUncaughtExceptionHandler (new UncaughtExceptionHandler () {@ Override public void uncaughtException (Thread arg0, Throwable e) {// TODO Auto-generated method stub System. out. println ("= Exception:" + e. getMessage (); String message = e. getMessage (); if (control = MAX) {return;} else if ("OK ". equals (message) {return;} else if ("error ". equals (message) {n Ew Thread () {public void run () {try {System. out. println ("starts sleep. "); Thread. sleep (1*1000); control ++; System. out. println ("sleep ends, control:" + control); myTask (data);} catch (InterruptedException e) {e. printStackTrace ();}};}. start () ;}else {return ;}}); myTask (data) ;}@ SuppressWarnings ("finally") public void myTask (int data) {boolean flag = true; try {System. out. println (4/data);} catch (Exception e) {flag = false;} finally {if (flag) {throw new RuntimeException ("OK ");} else {throw new RuntimeException ("error") ;}} public static void main (String [] args) {ExecutorService exec = Executors. newCachedThreadPool (); ThreadMonitor threadMonitor = new ThreadMonitor (0); exec.exe cute (threadMonitor); exec. shutdown ();}}

Running result:

= Exception: error
Start sleep.
Sleep ends, control: 1
= Exception: error
Start sleep.
Sleep ends, control: 2
= Exception: error
Start sleep.
Sleep ends, control: 3
= Exception: error

 

In this case, the thread interruption caused by Zero Divisor can be captured normally. Where:

(1) provideInterfaceThe UncaughtExceptionHandler Interface contains an uncaughtException method that can detect the termination of an uncaptured exception. Definition:

UncaughtExceptionHandler interface:Public static interface Thread. UncaughtExceptionHandler

UncaughtException method:Public void uncaughtException (Thread t, Throwable e)

(2) The uncaughtException method will capture thread exceptions. In this case, overwrite the method to set custom processing methods.

(3) set UncaughtExceptionHandler to handle exceptions:

Method 1: Use the static method provided by Thread to setDefaultException Handling:Public static void setDefaultUncaughtExceptionHandler (Thread. UncaughtExceptionHandler ux)

Method 2: procedure:Public void setUncaughtExceptionHandler (Thread. UncaughtExceptionHandler eh)

(4) The UncaughtExceptionHandler Exception Handling must be set in the run () method. Otherwise, the thread exception cannot be caught.

(5) Reference Links:

JAVA memory pool boot program: http://www.cnblogs.com/zhujiabin/p/5404771.html

JAVA multi-thread Exception Handling: http://blog.csdn.net/u013256816/article/details/50417822

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.