Java多线程

自己的事情自己做,线程异常处理

2019-11-15  本文已影响0人  何甜甜在吗

之前使用线程执行任务的时候,总是忽略了线程异常的处理,直到最近看书

线程出现异常测试类

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】进行赋值,因此将进入最后一层条件,将异常打印到控制台中,对异常不做任何处理。
整个异常处理器调用链如下:


首先判断默认异常处理器【defaultUncaughtExceptionHandler】是不是为null,在判断线程组异常处理器【group】是不是为null,在判断自定义异常处理器【uncaughtExceptionHandler】是不是为null,都为null则在控制台打印异常

线程异常处理

分析了一下源码就知道如果想对任务执行过程中的异常进行处理一个就是让ThreadGroup不为null,另外一种思路就是让UncaughtExceptionHandler类型的变量值不为null。

线程组异常捕获处理器很适合为线程进行分组处理的场景,每个分组出现异常的处理方式不相同
设置完异常处理器后异常都能被捕获了,但是不知道为什么设置异常处理器后任务的执行顺序乱了,难道是因为为每个线程设置异常处理器的时间不同【想不通】

线程池异常处理

一般应用中线程都是通过线程池创建复用的,因此对线程池的异常处理就是为线程池工厂类【ThreadFactory实现类】生成的线程添加异常处理器

设计原则,为什么要由线程自身进行捕获

来自JVM的设计理念"线程是独立执行的代码片断,线程的问题应该由线程自己来解决,而不要委托到外部"。因此在Java中,线程方法的异常【即任务抛出的异常】,应该在线程代码边界之内处理掉,而不应该在线程方法外面由其他线程处理

线程执行Callable任务

前面介绍的是线程执行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的状态最终被设置为EXCEPTIONAL,因此方法将捕获的任务抛出【new ExecutionException((Throwable)x)】
总结:
Callable任务抛出的异常能在代码中通过try-catch捕获到,但是只有调用get方法后才能捕获到

image.png

附往期文章:欢迎你的阅读、点赞、评论

并发相关
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进行截图

其他:
1. 使用try-with-resources优雅关闭资源
2. 老板,用float存储金额为什么要扣我工资

上一篇下一篇

猜你喜欢

热点阅读