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

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

线程出现异常测试类

  • 任务类:Task.java

    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,将抛出一个异常

  • 线程测试类: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#dispatchUncaughtException

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

首先判断默认异常处理器【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中,线程方法的异常【即任务抛出的异常】,应该在线程代码边界之内处理掉,而不应该在线程方法外面由其他线程处理

线程执行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存储金额为什么要扣我工资

猜你喜欢

转载自juejin.im/post/5dcd694d51882510a2331317