Task cancellation for Java concurrent programming (eight)

Source: Internet
Author: User
Tags stack trace

Handling an unhealthy thread abort

When a single-threaded console program terminates due to an uncaught exception, it is easy to understand that the program will stop running and produce very different stack trace information from the normal output of the program. However, if a thread in a concurrent program fails, it is usually not so obvious. Stack trace information may be output in the console, but no one will be observing the console. In addition, when a thread fails, the application may still appear to be working, so this failure is likely to be ignored. The next issue is to monitor and prevent "missing" threads in the program.

The main cause of premature thread death is runtimeexception.

We can build a worker thread inside the online pool. If the task throws an unchecked exception, it will cause the thread to end. The framework might replace the worker thread with a new thread, or it might not. Because the thread pool is shutting down, or there are enough threads to meet the needs.

When you write a worker thread class that submits a task to the thread pool, or when you invoke untrusted external code, such as a dynamically loaded plug-in. Use one of these methods to avoid a poorly written task or plug-in that does not affect the entire thread that invokes it.

public void Run () {Throwable thrown = null;try {while (!isinterrupted ()) RunTask (Gettaskfromworkqueue ());} catch ( Throwable e) {thrown = e;} finally {threadexited (this, thrown);}}

handling of uncaught exceptions

The above is an active way to resolve unchecked exceptions, and Uncaughtexceptionhandler is also available in the thread API, which detects the end of a purebred due to an uncaught exception. These two situations are complementary. By combining the two together, it is possible to effectively prevent thread leaks


When a thread exits due to an uncaught exception, the JVM reports this event to the Uncaughtexceptionhandler exception handler provided by the application. If no exception handler is provided. Then the default behavior is to output stack trace information to System.err.

public class Testthread extends Thread {@Overridepublic void Setuncaughtexceptionhandler (Uncaughtexceptionhandler eh) { TODO auto-generated Method Stubsuper.setuncaughtexceptionhandler (new Uncaughtexceptionhandler () {@Overridepublic void Uncaughtexception (Thread t, Throwable e) {//TODO auto-generated Method stub}});}
The most common response is to write an error message and the corresponding stack trace information to the application log. You can also take a more direct response. For example, try restarting the thread, shutting down the application, or performing other operations such as repair or diagnostics.

Import Java.util.logging.level;import Java.util.logging.logger;public class Uehlogger implements Thread.uncaughtexceptionhandler {@Overridepublic void uncaughtexception (Thread t, Throwable e) {//TODO auto-generated Method Stublogger logger = Logger.getanonymouslogger (); Logger.log (Level.severe, "Thread terminted with exception" + T.getname (), E);}}

To set a uncaughtexceptionhandler for all threads in the thread pool. You need to provide a threadfactory to the Threadpoolexecutor constructor. In order to enable only the thread owner to change the thread'sUncaughtexceptionhandler。


Import Java.lang.thread.uncaughtexceptionhandler;import Java.util.concurrent.blockingqueue;import Java.util.concurrent.threadfactory;import Java.util.concurrent.threadpoolexecutor;import Java.util.concurrent.timeunit;public class Examplethreadpool extends Threadpoolexecutor {public Examplethreadpool ( int corepoolsize, int maximumpoolsize,long keepalivetime, timeunit unit,blockingqueue<runnable> workQueue, Threadfactory threadfactory) {super (corepoolsize, Maximumpoolsize, KeepAliveTime, Unit, workqueue,threadfactory);// TODO auto-generated constructor stub}public static void Main (string[] args) {threadfactory tf = new Threadfactory () {@Over Ridepublic thread Newthread (Runnable r) {//TODO auto-generated method Stubthread t = new Thread (r); t.setuncaughtexception Handler (New Uncaughtexceptionhandler () {@Overridepublic void uncaughtexception (Thread t, Throwable e) {//TODO auto-generated method stub}}); return t;}}; New Examplethreadpool (Corepoolsize, Maximumpoolsize, Keepalivetime,unit,WorkQueue, TF);}} 
Just give the example of Threadfactory.

It is also important to note that only the task submitted through execute will be able to give the exception it reported to the uncaught exception handler. Tasks submitted through submit, whether thrown unchecked or checked, will be considered part of the return status of the task. If a task submitted by submit ends by throwing an exception, the exception will be future.get encapsulated in Executionexception,


Reference: Java concurrency programming combat

Task cancellation for Java concurrent programming (eight)

Related Article

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.