以前使用线程执行任务的时候,老是忽略了线程异常的处理,直到最近看书java
任务类:Task.javamysql
public class Task implements Runnable {
private int i;
public Task(int i) {
this.i = i;
}
@Override
public void run() {
if (i == 5) {
//System.out.println("throw exception");
throw new IllegalArgumentException();
}
System.out.println(i);
}
}
复制代码
若是i==5,将抛出一个异常sql
线程测试类:TaskTest.java数据库
public class TestTask {
public static void main(String[] args) {
int i = 0;
while (true) {
if (i == 10) break;
try {
new Thread(new Task(i++)).start();
} catch (Exception e) {
System.out.println("catch exception...");
}
}
}
}
复制代码
经过使用try-catch,尝试对抛出的异常进行捕获设计模式
测试结果缓存
Connected to the target VM, address: '127.0.0.1:64551', transport: 'socket'
0
1
2
3
4
6
7
8
9
Exception in thread "pool-1-thread-1" java.lang.IllegalArgumentException
at com.h2t.study.thread.Task.run(Task.java:21)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
复制代码
异常没有被捕获,只是在控制台打印了异常,而且不影响后续任务的执行 emmmm这是为何呢,捕获不到异常就不知道程序出错了,到时候哪天有个任务不正常排查都排查不到,这样是要不得的。看一下Thread这个类,有个叫dispatchUncaughtException的方法,做用如其名,分发未捕获的异常,把这段代码揪出来:Thread#dispatchUncaughtExceptionbash
private void dispatchUncaughtException(Throwable e) {
getUncaughtExceptionHandler().uncaughtException(this, e);
}
复制代码
find usage是找不到该方法在哪里调用的,由于这个方法只被JVM调用 Thread#getUncaughtExceptionHandler: 获取UncaughtExceptionHandler接口实现类并发
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return uncaughtExceptionHandler != null ?
uncaughtExceptionHandler : group;
}
复制代码
UncaughtExceptionHandler是Thread中定义的接口,在Thread类中uncaughtExceptionHandler默认是null,所以该方法将返回group,即实现了UncaughtExceptionHandler接口的ThreadGroup类 UncaughtExceptionHandler#uncaughtException: ThreadGroup类的uncaughtException方法实现框架
public void uncaughtException(Thread t, Throwable e) {
if (parent != null) {
parent.uncaughtException(t, e);
} else {
Thread.UncaughtExceptionHandler ueh =
Thread.getDefaultUncaughtExceptionHandler();
if (ueh != null) {
ueh.uncaughtException(t, e);
} else if (!(e instanceof ThreadDeath)) {
System.err.print("Exception in thread \""
+ t.getName() + "\" ");
e.printStackTrace(System.err);
}
}
}
复制代码
由于在Thread类中没有对group【parent】和defaultUncaughtExceptionHandler【Thread.getDefaultUncaughtExceptionHandler】进行赋值,所以将进入最后一层条件,将异常打印到控制台中,对异常不作任何处理。 整个异常处理器调用链以下: socket
首先判断默认异常处理器【defaultUncaughtExceptionHandler】是否是为null,在判断线程组异常处理器【group】是否是为null,在判断自定义异常处理器【uncaughtExceptionHandler】是否是为null,都为null则在控制台打印异常
分析了一下源码就知道若是想对任务执行过程当中的异常进行处理一个就是让ThreadGroup不为null,另一种思路就是让UncaughtExceptionHandler类型的变量值不为null。
异常处理器:ExceptionHandler.java
private static class ExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("异常捕获到了:" + e);
}
}
复制代码
设置默认异常处理器
Thread.setDefaultUncaughtExceptionHandler((t, e) -> System.out.println("异常捕获到 了: " + e));
int i = 0;
while (true) {
if (i == 10) break;
Thread thread = new Thread(new Task(i++));
thread.start();
}
复制代码
打印结果:
0
2
1
3
9
6
7
4
异常捕获到了:java.lang.IllegalArgumentException
8
复制代码
经过设置默认异常就不须要为每一个线程都设置一次了
设置自定义异常处理器
Thread t = new Thread(new Task(i++));
t.setUncaughtExceptionHandler(new ExceptionHandler());
复制代码
打印结果:
0
2
4
异常捕获到了:java.lang.IllegalArgumentException
6
1
3
7
9
8
复制代码
设置线程组异常处理器
MyThreadGroup myThreadGroup = new MyThreadGroup("测试线程线程组");
Thread t = new Thread(myThreadGroup, new Task(i++))
复制代码
自定义线程组:MyThreadGroup.java
private static class MyThreadGroup extends ThreadGroup {
public MyThreadGroup(String name) {
super(name);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("捕获到异常了:" + e);
}
}
复制代码
打印结果:
1
2
0
4
3
6
7
8
9
捕获到异常了:java.lang.IllegalArgumentException
复制代码
线程组异常捕获处理器很适合为线程进行分组处理的场景,每一个分组出现异常的处理方式不相同 设置完异常处理器后异常都能被捕获了,可是不知道为何设置异常处理器后任务的执行顺序乱了,难道是由于为每一个线程设置异常处理器的时间不一样【想不通】
通常应用中线程都是经过线程池建立复用的,所以对线程池的异常处理就是为线程池工厂类【ThreadFactory实现类】生成的线程添加异常处理器
默认异常处理器
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
ExecutorService es = Executors.newCachedThreadPool();
es.execute(new Task(i++))
复制代码
自定义异常处理器
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
threadPoolExecutor.setThreadFactory(new MyThreadFactory());
threadPoolExecutor.execute(new Task(i++));
复制代码
自定义工厂类:MyThreadFactory.java
private static class MyThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread();
//自定义UncaughtExceptionHandler
t.setUncaughtExceptionHandler(new ExceptionHandler());
return t;
}
}
复制代码
来自JVM的设计理念"线程是独立执行的代码片段,线程的问题应该由线程本身来解决,而不要委托到外部"。所以在Java中,线程方法的异常【即任务抛出的异常】,应该在线程代码边界以内处理掉,而不该该在线程方法外面由其余线程处理
前面介绍的是线程执行Runnable类型任务的状况,众所周知,还有一种有返回值的Callable任务类型 测试代码:TestTask.java
public class TestTask {
public static void main(String[] args) {
int i = 0;
while (true) {
if (i == 10) break;
FutureTask<Integer> task = new FutureTask<>(new CallableTask(i++));
Thread thread = new Thread(task);
thread.setUncaughtExceptionHandler(new ExceptionHandler());
thread.start();
}
}
private static class ExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("异常捕获到了:" + e);
}
}
}
复制代码
打印结果:
Disconnected from the target VM, address: '127.0.0.1:64936', transport: 'socket'
0
1
2
3
4
6
7
8
9
复制代码
观察结果,异常没有被捕获,thread.setUncaughtExceptionHandler(new ExceptionHandler())方法设置无效,emmmmm,这又是为何呢,在问为何就是十万个为何儿童了。查看FutureTask的run方法,FutureTask#run:
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
复制代码
FutureTask#setException:
protected void setException(Throwable t) {
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
//将异常设置给outcome变量
outcome = t;
//设置任务的状态为EXCEPTIONAL
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
finishCompletion();
}
}
复制代码
看到catch这段代码,当执行任务捕获到异常的时候,会将任务的处理结果设置为null,而且调用setException方法对捕获的异常进行处理,由于setUncaughtExceptionHandler只对未捕获的异常进行处理,FutureTask已经对异常进行了捕获处理,所以调用setUncaughtExceptionHandler捕获异常无效 对任务的执行结果调用get方法:
int i = 0;
while (true) {
if (i == 10) break;
FutureTask<Integer> task = new FutureTask<>(new CallableTask(i++));
Thread thread = new Thread(task);
thread.setUncaughtExceptionHandler(new ExceptionHandler());
thread.start();
//打印结果
try {
System.out.println(task.get());
} catch (Exception e) {
System.out.println("异常被抓住了, e: " + e);
}
}
复制代码
执行结果将会将捕获到的异常打印出来,执行结果:
0
1
2
3
4
异常被抓住了, e: java.util.concurrent.ExecutionException: java.lang.IllegalArgumentException
6
7
Disconnected from the target VM, address: '127.0.0.1:50900', transport: 'socket'
8
9
复制代码
FutureTask#get:
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
//未完成等待任务执行完成
s = awaitDone(false, 0L);
return report(s);
}
复制代码
FutureTask#report:
private V report(int s) throws ExecutionException {
Object x = outcome;
if (s == NORMAL)
return (V)x;
if (s >= CANCELLED)
throw new CancellationException();
throw new ExecutionException((Throwable)x);
}
复制代码
outcome在setException方法中被设置为了异常,而且s为state的状态最终8被设置为EXCEPTIONAL,所以方法将捕获的任务抛出【new ExecutionException((Throwable)x)】
总结:
Callable任务抛出的异常能在代码中经过try-catch捕获到,可是只有调用get方法后才能捕获到
并发相关
1.为何阿里巴巴要禁用Executors建立线程池?
设计模式相关:
1. 单例模式,你真的写对了吗?
2. (策略模式+工厂模式+map)套餐 Kill 项目中的switch case
JAVA8相关:
1. 使用Stream API优化代码
2. 亲,建议你使用LocalDateTime而不是Date哦
数据库相关:
1. mysql数据库时间类型datetime、bigint、timestamp的查询效率比较
2. 很高兴!终于踩到了慢查询的坑
高效相关:
1. 撸一个Java脚手架,一统团队项目结构风格
日志相关:
1. 日志框架,选择Logback Or Log4j2?
2. Logback配置文件这么写,TPS提升10倍
工程相关:
1. 闲来无事,动手写一个LRU本地缓存
2. Redis实现点赞功能模块
3. JMX可视化监控线程池
4. 权限管理 【SpringSecurity篇】
5. Spring自定义注解从入门到精通
6. java模拟登录优酷
7. QPS这么高,那就来写个多级缓存吧
8. java使用phantomjs进行截图