JAVA Thread Exception Monitoring

Source: Internet
Author: User

Scene Description: A single-threaded program can use Try...catch to capture the program's exceptions, while in multi-threaded programs It is not possible to use try...catch capture.

Example 1: Multithreaded exception, unable to capture problem using Try...catch

 Public classNocaughtthreadImplementsrunnable{@Override Public voidrun () {System.out.println (3/2); System.out.println (3/0); System.out.println (3/1); }         Public Static voidMain (string[] args) {Try{thread thread=NewThread (NewNocaughtthread ());        Thread.Start (); } Catch(Exception e) {System.out.println ("==exception:" +e.getmessage ()); }    }}

Operation 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 a program to set an exception capture, at which point Try...catch cannot capture the thread's exception. At this point, if the thread terminates execution because of an exception, the exception cannot be detected. The reason for this is that the thread class run () method does not throw any check-type exceptions, but itself may be aborted because of an exception.

Second, there are roughly two ways to solve the problem: ① set the corresponding exception handling in run (), the active method to resolve the non-detection exception, ②thread Class API provides Interface interface Uncaughtexceptionhandler, The interface contains the Uncaughtexception method, which detects an uncaught exception and the end of the case;

Example 2: Proactive Detection of exceptions

ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classInitiativecaught { Public Static voidMain (string[] args) {initialtivethread initialtivethread=NewInitialtivethread (); Executorservice exec=Executors.newcachedthreadpool ();        Exec.execute (Initialtivethread);    Exec.shutdown (); }}classInitialtivethreadImplementsRunnable {@Override Public voidrun () {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 voidThreaddeal (Runnable R, Throwable t) {System.out.println ("==exception:" +t.getmessage ()); }  }

Operation Result:

1
==exception:/By zero

This is the time to proactively catch the exception and do the processing to get the desired result.

The sample 3:thread Class API provides an Uncaughtexceptionhandler interface to catch exceptions that require a thread exception to be detected and an exception to be set to repeat the call three times after the thread is terminated.

ImportJava.lang.Thread.UncaughtExceptionHandler;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classThreadmonitorImplementsRunnable {Private intData//can be set by constructing the pass parameter    Private intControl = 0; Private Static Final intMAX = 3;//set the number of retries         PublicThreadmonitor (inti) { This. data =i; }     PublicThreadmonitor () {//TODO auto-generated Constructor stub} @Override Public voidrun () {Thread.setdefaultuncaughtexceptionhandler (NewUncaughtexceptionhandler () {@Override Public voiduncaughtexception (Thread arg0, Throwable e) {//TODO auto-generated Method StubSystem.out.println ("==exception:" +e.getmessage ()); String message=E.getmessage (); if(control==MAX) {                    return ; }Else if("OK". Equals (Message)) {                    return ; }Else if("Error". Equals (Message)) {                    NewThread () { Public voidrun () {Try{System.out.println ("Start sleeping. "); Thread.Sleep (1 * 1000); Control++ ; System.out.println ("Sleep over, control:" +control);                            MyTask (data); } Catch(interruptedexception e) {e.printstacktrace ();                    }                        };                }.start (); }Else{                    return ;                  }            }        });            MyTask (data); } @SuppressWarnings ("Finally")     Public voidMyTask (intdata) {        BooleanFlag =true ; Try{System.out.println (6 mdata); } Catch(Exception e) {flag=false ; } finally {            if(flag) {Throw NewRuntimeException ("OK"); }Else{                Throw NewRuntimeException ("Error"); }        }    }         Public Static voidMain (string[] args) {Executorservice exec=Executors.newcachedthreadpool (); Threadmonitor Threadmonitor=NewThreadmonitor (0);        Exec.execute (Threadmonitor);    Exec.shutdown (); }}

Operation Result:

==exception:error
Start your sleep.
End of sleep, control:1
==exception:error
Start your sleep.
End of sleep, control:2
==exception:error
Start your sleep.
End of sleep, Control:3
==exception:error

At this point, you can normally capture interrupts caused by a line routines divisor of zero. which

(1) The Interface interface Uncaughtexceptionhandler is provided in the Thread class API, which contains a uncaughtexception method that detects a condition that is terminated by an uncaught exception. Defined as follows:

Uncaughtexceptionhandler interface: Public static interface Thread.uncaughtexceptionhandler

Uncaughtexception method: Public void Uncaughtexception (Thread t, throwable e)

(2) The Uncaughtexception method captures the thread's exception and needs to override the method to set the custom processing.

(3) Set Uncaughtexceptionhandler exception handling:

Method One: Set the default exception handling by using the static Statics method provided by thread: publicstatic void Setdefaultuncaughtexceptionhandler ( Thread.uncaughtexceptionhandler UX)

Way two: By method: Publicvoid Setuncaughtexceptionhandler (Thread.uncaughtexceptionhandler eh)

(4) Uncaughtexceptionhandler exception handling needs to be set within the run () method, otherwise the exception of the thread cannot be caught.

(5) Reference Links:

Java under Memory Pool launcher: http://www.cnblogs.com/zhujiabin/p/5404771.html

Multithreading exception handling under Java: http://blog.csdn.net/u013256816/article/details/50417822

JAVA Thread Exception Monitoring

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.