美文网首页
线程的异常处理机制

线程的异常处理机制

作者: tracy_668 | 来源:发表于2021-10-17 15:28 被阅读0次

未捕获异常去哪里了?

一个异常被抛出后,如果没有被捕获处理,那么会一直向上抛出,直到被main()/Thread.run()抛出。异常被main()/Thread.run() 抛出后,会由虚拟机调用Thread 的 dispatchUncaughtException方法:

    /**
     * 向 handler 分派未捕获的异常。 该方法仅由JVM调用。
     */
    private void dispatchUncaughtException(Throwable e) {
        getUncaughtExceptionHandler().uncaughtException(this, e);
    }

    // 获取未捕获异常处理的 handler,如果没有设置则返回当前线程所属的ThreadGroup
    public UncaughtExceptionHandler getUncaughtExceptionHandler() {
        return uncaughtExceptionHandler != null ?
            uncaughtExceptionHandler : group;
    }

ThreadGroup继承自 UncaughtExceptionHandler,实现了默认的处理方法:

    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)) { // 没有配置handler时的处理方式
                System.err.print("Exception in thread \""
                                 + t.getName() + "\" ");
                e.printStackTrace(System.err);
            }
        }
    }

当有异常被main()/Thread.run() 抛出后,JVM会调用 dispatchUncaughtException 来寻找handler进行处理。而如果没有自定义hanlder进行处理,则会调用 System.err 进行输出。

线程对异常的处理

本文将线程实现分为两种,无返回值的Runnable实现 和 有返回值的FutureTask实现。然后分为 Thread 、ThreadPoolExecutor 和 ScheduledThreadPoolExecutor 三种情况来讨论异常的处理。

一、Thread 异常处理

Thread 线程的有很多种实现形式,基于 Runnable 的没有返回值的线程,无法在主线程感知到异常,没有捕获的异常只会输出到控制台,如果没有捕获异常,进行处理或日志记录,会造成异常丢失。有返回值的 FutureTask ,未捕获的异常,会在获取返回值时传递给主线程。

  1. 主线程无法捕获子线程异常
public static void catchInMainThread(){
    try {
        Thread thread = new Thread(() -> {
            System.out.println( 1 / 0);
        });
        thread.start();
    } catch (Exception e1) {
        System.out.println("catched exception in main thread");
    }
}
// 代码一输出
Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero
    at ThreadExecptionTest.lambda$0(ThreadExecptionTest.java:14)
    at java.lang.Thread.run(Thread.java:745)

上述代码无法捕获到异常,根据开篇介绍的默认处理机制,异常在子线程的Thread.run()方法中抛出后,JVM会调用 dispatchUncaughtException 方法最终输出到控制台。

2. 子线程处理Runnable异常
public static void catchInRunThread() {
    Thread thread = new Thread(() -> {
        try {
            System.out.println(1 / 0);
        } catch (Exception e1) {
            // 异常处理,日志记录等
            System.out.println("catched exception in child thread");
        }
    });
    thread.start();
}
// 代码二输出结果
catched exception in child thread

代码二展示了线程内按需处理异常的方式,这是一种推荐的线程内异常处理方法。

3. 主线程处理FutureTask异常

public static void catchInFuture() {
    FutureTask<Integer> futureTask = new FutureTask<>(() ->  {
        return 1/0;
    });
    
    Thread thread = new Thread(futureTask);
    thread.start();
    try {
        futureTask.get();
    } catch (InterruptedException | ExecutionException e) {
        System.out.println("catched exception in main thread by future");
//          e.printStackTrace();
    }
}

输出如下:

catched exception in main thread by future

FutureTask 的异常成功在主线程里处理。
对应的源码:

  /**
     * Causes this future to report an {@link ExecutionException}
     * with the given throwable as its cause, unless this future has
     * already been set or has been cancelled.
     *
     * <p>This method is invoked internally by the {@link #run} method
     * upon failure of the computation.
     *
     * @param t the cause of failure
     */
    protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }

4. 配置默认线程异常处理方式

public static void catchByExceptionHandler() {
    Thread thread = new Thread(() -> {
            System.out.println(1 / 0);
    });
    UncaughtExceptionHandler eh = new MyUncaughtExceptionHandler();
    thread.setUncaughtExceptionHandler(eh);
    thread.start();
}

static class MyUncaughtExceptionHandler implements UncaughtExceptionHandler{

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        // 异常处理,日志记录等
        System.out.println("catched exception in ExceptionHandler");
    }
    
}
// 代码三输出:
catched exception in ExceptionHandler

使用UncaughtExceptionHandler 来处理未捕获异常也是一个可参考的方案。

二、ThreadPoolExecutor 异常处理

public class ThreadPoolExecutorExceptionTest {

    public static void main(String[] args) throws InterruptedException, IOException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
        executeThreadPoolExecutor(executor);
        Thread.sleep(100);
        submitThreadPoolExecutorWithOutGet(executor);
        Thread.sleep(100);
        submitThreadPoolExecutorAndGet(executor);
        Thread.sleep(100);
        executor.shutdown();
    }
    // Runnable子线程没有捕获异常
    static void executeThreadPoolExecutor(ThreadPoolExecutor executor) {
        System.out.println("\n*****executeThreadPoolExecutor*****");
        executor.execute(() -> {
            System.out.println(1 / 0);
        });
    }
    // Callable不获取返回值
    static void submitThreadPoolExecutorWithOutGet(ThreadPoolExecutor executor) {
        System.out.println("\n*****submitThreadPoolExecutorWithOutGet*****");
        executor.submit(() -> {
            System.out.println(1 / 0);
        });
    }
    // Callable获取返回值
    static void submitThreadPoolExecutorAndGet(ThreadPoolExecutor executor) {
        System.out.println("\n*****submitThreadPoolExecutorAndGet*****");
        Future<?> future = executor.submit(() -> {
            System.out.println(1 / 0);
        });

        try {
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            System.out.println("catched exception in main thread by future");
//          e.printStackTrace();
        }
    }
}

上面展示了三种ThreadPoolExecutor提交任务的形式,输出如下:

*****executeThreadPoolExecutor*****
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero
    at test.ThreadTest.lambda$1(ThreadTest.java:65)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

*****submitThreadPoolExecutorWithOutGet*****

*****submitThreadPoolExecutorAndGet*****
catched exception in main thread by future

直接用execute执行Runnable方法,如果主线程里的异常未捕获,将被默认handler输出到控制台,与Thread执行任务类似。如果使用submit执行FutureTask任务,而不调用get方法获取返回值,则会造成异常丢失现象。使用FutureTask只有调用get方法才能感知到子线程是否正常执行。因此,为了确保任务顺利执行,需使用get方法确认返回结果是否有异常抛出。

三、ScheduledThreadPoolExecutor 异常处理

之所以要将ScheduledThreadPoolExecutor 线程池单独拿出来讲,是因为ScheduledThreadPoolExecutor 的调度方法与普通线程池执行方法不同,有着特殊的规则。
ScheduledThreadPoolExecutor 有个三个调度方法:schedule、scheduleAtFixedRate、scheduleWithFixedDelay,schedule方法有个重载方法,可以传Callable执行

谨防 ScheduledThreadPoolExecutor 异常丢失

从上图我们可以看到,这几个方法都有返回值为 ScheduledFuture ,根据前面的分析我们知道有返回值的Future可以在获取返回值是捕获到异常,不获取返回值就会造成异常丢失。我们来验证一下:

public class ScheduledPoolExecptionTest {
    public static void main(String[] args) {
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
        schedule(executor);
    }
    
    static void schedule(ScheduledThreadPoolExecutor executor) {
        executor.schedule(() -> {
            int n = 1/0; // 应该抛出异常
        }, 10, TimeUnit.NANOSECONDS);
    }
}

用ScheduledThreadPoolExecutor的schedule方法执行Runnable,上述代码没有任何输出,异常消失了。这是平时我们使用调度线程池很容易犯的一个错误,这种异常消失在生产环境中将产生难以发现的问题。
ScheduledThreadPoolExecutor 的其他几个调度方法也会产生类似的问题。由于我们执行的是Runnable任务,往往不会调用future的get方法,因此在开发中,应该多加小心这种异常吞并。避免产生此问题,尽量在线程内捕获异常并处理;
ScheduledThreadPoolExecutor 的execute方法和submit继承自
ThreadPoolExecutor,异常处理机制一样。

总结

不管是Thread 、ThreadPoolExecutor 还是ScheduledThreadPoolExecutor,都应秉承线程内部处理的原则,做到自己的事情自己办。正确的处理、记录异常,及时的发现问题,避免不必要的麻烦。

相关文章

  • 线程的异常处理机制

    前言 分析线程对异常的处理机制,首先要了解Java自身的异常处理机制,关于 try、catch、finally、t...

  • 线程的异常处理机制

    未捕获异常去哪里了? 一个异常被抛出后,如果没有被捕获处理,那么会一直向上抛出,直到被main()/Thread....

  • Java异常处理机制

    什么是异常处理机制: 异常处理机制: 让程序发生异常时,按照代码预先设定的异常处理逻辑,针对性地处理异常,让程序尽...

  • 异常处理

    JAVA严格的异常处理机制和类型检查机制 异常处理手贱异常非手贱异常 异常链处理 异常是在程序出错的时候能知道程序...

  • java 异常

    Java中异常处理是识别及响应错误的机制。有效地异常处理能使程序更加健壮。异常处理是非功能性需求。 异常的处理机制...

  • Java线程的异常处理机制

    启动一个Java程序,本质上是运行某个Java类的main方法。我们写一个死循环程序,跑起来,然后运行jvisua...

  • Java多线程异常处理

    线程异常处理 Java中每个线程的异常处理是相互独立的,一个线程产生的异常不会影响其他线程的正常运行。因此,也不能...

  • Android多线程消息处理机制

    Android多线程消息处理机制(一) Looper、Thread专题 Android多线程消息处理机制(二) L...

  • Java 异常

    异常处理机制 异常处理模型:终止模型:当异常发生时,就进入异常处理程序,处理结束并不返回异常发生位置继续执行;恢复...

  • Java 线程池的异常处理机制

    一、前言 线程池技术是服务器端开发中常用的技术。不论是直接还是间接,各种服务器端功能的执行总是离不开线程池的调度。...

网友评论

      本文标题:线程的异常处理机制

      本文链接:https://www.haomeiwen.com/subject/fklwoltx.html