JAVA多线程之UncaughtExceptionHandler——处理非正常的线程中止
JAVA多线程之UncaughtExceptionHandler——处理非正常的线程中止
背景
当单线程的程序发生一个未捕获的异常时我们可以采用try....catch进行异常的捕获,但是在多线程环境中,线程抛出的异常是不能用try....catch捕获的,这样就有可能导致一些问题的出现,比如异常的时候无法回收一些系统资源,或者没有关闭当前的连接等等。
package com.exception; public class NoCaughtThread
{
public static void main(String[] args)
{
try
{
Thread thread = new Thread(new Task());
thread.start();
}
catch (Exception e)
{
System.out.println("==Exception: "+e.getMessage());
}
}
} class Task implements Runnable
{
@Override
public void run()
{
System.out.println(3/2);
System.out.println(3/0);
System.out.println(3/1);
}
}
运行结果:
1
Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero
at com.exception.Task.run(NoCaughtThread.java:25)
at java.lang.Thread.run(Unknown Source)
可以看到在多线程中通过try....catch试图捕获线程的异常是不可取的。
Thread的run方法是不抛出任何检查型异常的,但是它自身却可能因为一个异常而被中止,导致这个线程的终结。
首先介绍一下如何在线程池内部构建一个工作者线程,如果任务抛出了一个未检查异常,那么它将使线程终结,但会首先通知框架该现场已经终结。然后框架可能会用新的线程来代替这个工作线程,也可能不会,因为线程池正在关闭,或者当前已有足够多的线程能满足需要。当编写一个向线程池提交任务的工作者类线程类时,或者调用不可信的外部代码时(例如动态加载的插件),使用这些方法中的某一种可以避免某个编写得糟糕的任务或插件不会影响调用它的整个线程。
主动方法解决
package com.exception; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class InitiativeCaught
{
public void threadDeal(Runnable r, Throwable t)
{
System.out.println("==Exception: "+t.getMessage());
} 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 static void main(String[] args)
{
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new InitiativeCaught().new InitialtiveThread());
exec.shutdown();
} }
运行结果:
1
==Exception: / by zero
Thread API 解决
上面介绍了一种主动方法来解决未检测异常。在Thread ApI中同样提供了UncaughtExceptionHandle,它能检测出某个由于未捕获的异常而终结的情况。这两种方法是互补的,通过将二者结合在一起,就能有效地防止线程泄露问题。
package com.exception; import java.lang.Thread.UncaughtExceptionHandler; public class WitchCaughtThread
{
public static void main(String args[])
{
Thread thread = new Thread(new Task());
thread.setUncaughtExceptionHandler(new ExceptionHandler());
thread.start();
}
} class ExceptionHandler implements UncaughtExceptionHandler
{
@Override
public void uncaughtException(Thread t, Throwable e)
{
System.out.println("==Exception: "+e.getMessage());
}
}
运行结果:
1
==Exception: / by zero
同样可以为所有的Thread设置一个默认的UncaughtExceptionHandler,通过调用Thread.setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)方法,这是Thread的一个static方法。
package com.exception; import java.lang.Thread.UncaughtExceptionHandler; public class WitchCaughtThread
{
public static void main(String args[])
{
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
Thread thread = new Thread(new Task());
thread.start();
}
} class ExceptionHandler implements UncaughtExceptionHandler
{
@Override
public void uncaughtException(Thread t, Throwable e)
{
System.out.println("==Exception: "+e.getMessage());
}
}
运行结果:
1
==Exception: / by zero
线程池的异常捕获
execute方法提交任务
这样做不能捕获到异常:
public class ExecuteCaught
{
public static void main(String[] args)
{
ExecutorService exec = Executors.newCachedThreadPool();
Thread thread = new Thread(new Task());
thread.setUncaughtExceptionHandler(new ExceptionHandler());
exec.execute(thread);
exec.shutdown();
}
}
运行结果:
1
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero
at com.exception.Task.run(NoCaughtThread.java:25)
at java.lang.Thread.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
这时需要将异常的捕获封装到Runnable或者Callable中,如下所示:
package com.exception; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class ExecuteCaught
{
public static void main(String[] args)
{
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new ThreadPoolTask());
exec.shutdown();
}
} class ThreadPoolTask implements Runnable
{
@Override
public void run()
{
Thread.currentThread().setUncaughtExceptionHandler(new ExceptionHandler());
System.out.println(3/2);
System.out.println(3/0);
System.out.println(3/1);
}
}
运行结果:
1
==Exception: / by zero
submit方法提交任务
只有通过execute提交的任务,才能将它抛出的异常交给UncaughtExceptionHandler,而通过submit提交的任务,无论是抛出的未检测异常还是已检查异常,都将被认为是任务返回状态的一部分。如果一个由submit提交的任务由于抛出了异常而结束,那么这个异常将被Future.get封装在ExecutionException中重新抛出。
package com.exception; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class SubmitCaught
{
public static void main(String[] args)
{
ExecutorService exec = Executors.newCachedThreadPool();
exec.submit(new Task());
exec.shutdown();
}
}
package com.exception; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class SubmitCaught
{
public static void main(String[] args)
{
ExecutorService exec = Executors.newCachedThreadPool();
exec.submit(new ThreadPoolTask());
exec.shutdown();
}
}
上面两段代码运行结果都是:
1
通过这个例子可以看到捕获的异常:
package com.exception; import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future; public class SubmitCaught
{
public static void main(String[] args)
{
ExecutorService exec = Executors.newCachedThreadPool();
Future<?> future = exec.submit(new Task());
exec.shutdown();
try
{
future.get();
}
catch (InterruptedException | ExecutionException e)
{
System.out.println("==Exception: "+e.getMessage());
}
}
}
运行结果:
1
==Exception: java.lang.ArithmeticException: / by zero
JAVA多线程之UncaughtExceptionHandler——处理非正常的线程中止的更多相关文章
- java多线程之:创建开启一个线程的开销
---->关于时间,创建线程使用是直接向系统申请资源的,这里调用系统函数进行分配资源的话耗时不好说.---->关于资源,Java线程的线程栈所占用的内存是在Java堆外的,所以是不受jav ...
- Java多线程之ConcurrentSkipListMap深入分析(转)
Java多线程之ConcurrentSkipListMap深入分析 一.前言 concurrentHashMap与ConcurrentSkipListMap性能测试 在4线程1.6万数据的条件下, ...
- JAVA多线程之wait/notify
本文主要学习JAVA多线程中的 wait()方法 与 notify()/notifyAll()方法的用法. ①wait() 与 notify/notifyAll 方法必须在同步代码块中使用 ②wait ...
- JAVA多线程之volatile 与 synchronized 的比较
一,volatile关键字的可见性 要想理解volatile关键字,得先了解下JAVA的内存模型,Java内存模型的抽象示意图如下: 从图中可以看出: ①每个线程都有一个自己的本地内存空间--线程栈空 ...
- java多线程之yield,join,wait,sleep的区别
Java多线程之yield,join,wait,sleep的区别 Java多线程中,经常会遇到yield,join,wait和sleep方法.容易混淆他们的功能及作用.自己仔细研究了下,他们主要的区别 ...
- Java多线程之Runnable与Thread
Java多线程之Thread与Runnable 一.Thread VS Runnable 在java中可有两种方式实现多线程,一种是继承Thread类,一种是实现Runnable接口:Thread类和 ...
- java多线程之wait和notify协作,生产者和消费者
这篇直接贴代码了 package cn.javaBase.study_thread1; class Source { public static int num = 0; //假设这是馒头的数量 } ...
- Java——多线程之Lock锁
Java多线系列文章是Java多线程的详解介绍,对多线程还不熟悉的同学可以先去看一下我的这篇博客Java基础系列3:多线程超详细总结,这篇博客从宏观层面介绍了多线程的整体概况,接下来的几篇文章是对多线 ...
- Java多线程之ReentrantLock重入锁简介与使用教程
转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6543947.html 我们知道,线程安全问题需要通过线程之间的同步来解决,而同步大多使用syncrhoize ...
随机推荐
- osg include lib -computer1
E:\\OpenSceneGraph\\OpenSceneGraph_3_6_install\\lib E:\\OpenSceneGraph\\3rdParty\\v140-x64\\lib Open ...
- 转 Java连接Oracle数据库的简单示例
https://www.cnblogs.com/joyny/p/11176643.html https://community.oracle.com/thread/4096458 import jav ...
- Spring AOP无法拦截Controller
参考@参考文章中的评论 首先,应该打开aop代理 <aop:aspectj-autoproxy proxy-target-class="true"/> 其次,应该讲ao ...
- ABAP DEMO ALVtree显示BOM层级
展示效果: *&---------------------------------------------------------------------* *& Report YCX ...
- Swoole练习 websocket
WEBSOCKET 服务端代码 //创建websocket服务器对象,监听0.0.0.0:9502端口 $ws = new swoole_websocket_server("0.0.0.0& ...
- 任务调度之Quartz.Net可视化界面
上一篇关于任务调度Quartz.Net的文章中介绍了其三个核心对象IScheduler.IJob和ITrigger,我们已经知道了其基本的使用方法,可以在控制台当中运行监控.但是在实际中我们往往需要有 ...
- Google BERT
概述 BERT的全称是Bidirectional Encoder Representation from Transformers,即双向Transformer的Encoder,因为decoder是不 ...
- 013 Android 实现流水灯功能+自定义控件的样式(可以复用)
1.介绍 (1)获取屏幕的焦点 android:focusable与android:focusableInTouchMode(获取屏幕焦点) 前者针对在键盘下操作的情况,如果设置为true,则键盘上下 ...
- [转帖]TPC-C解析系列04_TPC-C基准测试之数据库事务引擎的挑战
TPC-C解析系列04_TPC-C基准测试之数据库事务引擎的挑战 http://www.itpub.net/2019/10/08/3331/ OceanBase这次TPC-C测试与榜单上Oracl ...
- Quartz.Net—DateBuilder
定时框架中最重要的就是时间,我们也可以直接使用Cron这种事件格式. 使用其他的时间格式,就可以用DateBuilder快速的创建出需要的时间. 因为quartz是一个定时框架,所以对于操控时间 ...