JAVA多线程之UncaughtExceptionHandler——处理非正常的线程中止

当单线程的程序发生一个未捕获的异常时我们可以采用try....catch进行异常的捕获,但是在多线程环境中,线程抛出的异常是不能用try....catch捕获的,这样就有可能导致一些问题的出现,比如异常的时候无法回收一些系统资源,或者没有关闭当前的连接等等。

首先来看一个示例:

[java]  view plain copy
  1. package com.exception;  
  2.   
  3. public class NoCaughtThread  
  4. {  
  5.     public static void main(String[] args)  
  6.     {  
  7.         try  
  8.         {  
  9.             Thread thread = new Thread(new Task());  
  10.             thread.start();  
  11.         }  
  12.         catch (Exception e)  
  13.         {  
  14.             System.out.println("==Exception: "+e.getMessage());  
  15.         }  
  16.     }  
  17. }  
  18.   
  19. class Task implements Runnable  
  20. {  
  21.     @Override  
  22.     public void run()  
  23.     {  
  24.         System.out.println(3/2);  
  25.         System.out.println(3/0);  
  26.         System.out.println(3/1);  
  27.     }  
  28. }  
运行结果:

[plain]  view plain copy
  1. 1  
  2. Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero  
  3.     at com.exception.Task.run(NoCaughtThread.java:25)  
  4.     at java.lang.Thread.run(Unknown Source)  
可以看到在多线程中通过try....catch试图捕获线程的异常是不可取的。

Thread的run方法是不抛出任何检查型异常的,但是它自身却可能因为一个异常而被中止,导致这个线程的终结。
首先介绍一下如何在线程池内部构建一个工作者线程,如果任务抛出了一个未检查异常,那么它将使线程终结,但会首先通知框架该现场已经终结。然后框架可能会用新的线程来代替这个工作线程,也可能不会,因为线程池正在关闭,或者当前已有足够多的线程能满足需要。当编写一个向线程池提交任务的工作者类线程类时,或者调用不可信的外部代码时(例如动态加载的插件),使用这些方法中的某一种可以避免某个编写得糟糕的任务或插件不会影响调用它的整个线程。

[java]  view plain copy
  1. package com.exception;  
  2.   
  3. import java.util.concurrent.ExecutorService;  
  4. import java.util.concurrent.Executors;  
  5.   
  6. public class InitiativeCaught  
  7. {  
  8.     public void threadDeal(Runnable r, Throwable t)  
  9.     {  
  10.         System.out.println("==Exception: "+t.getMessage());  
  11.     }  
  12.       
  13.     class InitialtiveThread implements Runnable  
  14.     {  
  15.         @Override  
  16.         public void run()  
  17.         {  
  18.             Throwable thrown = null;  
  19.             try  
  20.             {  
  21.                 System.out.println(3/2);  
  22.                 System.out.println(3/0);  
  23.                 System.out.println(3/1);  
  24.             }  
  25.             catch(Throwable e)  
  26.             {  
  27.                 thrown =e;  
  28.             }  
  29.             finally{  
  30.                 threadDeal(this,thrown);  
  31.             }  
  32.         }  
  33.     }  
  34.       
  35.     public static void main(String[] args)  
  36.     {  
  37.         ExecutorService exec = Executors.newCachedThreadPool();  
  38.         exec.execute(new InitiativeCaught().new InitialtiveThread());  
  39.         exec.shutdown();  
  40.     }  
  41.   
  42. }  
运行结果:

[plain]  view plain copy
  1. 1  
  2. ==Exception: / by zero  
上面介绍了一种主动方法来解决未检测异常。在Thread ApI中同样提供了UncaughtExceptionHandle,它能检测出某个由于未捕获的异常而终结的情况。这两种方法是互补的,通过将二者结合在一起,就能有效地防止线程泄露问题。

如下:

[java]  view plain copy
  1. package com.exception;  
  2.   
  3. import java.lang.Thread.UncaughtExceptionHandler;  
  4.   
  5. public class WitchCaughtThread  
  6. {  
  7.     public static void main(String args[])  
  8.     {  
  9.         Thread thread = new Thread(new Task());  
  10.         thread.setUncaughtExceptionHandler(new ExceptionHandler());  
  11.         thread.start();  
  12.     }  
  13. }  
  14.   
  15. class ExceptionHandler implements UncaughtExceptionHandler  
  16. {  
  17.     @Override  
  18.     public void uncaughtException(Thread t, Throwable e)  
  19.     {  
  20.         System.out.println("==Exception: "+e.getMessage());  
  21.     }  
  22. }  
运行结果:

[plain]  view plain copy
  1. 1  
  2. ==Exception: / by zero  
同样可以为所有的Thread设置一个默认的UncaughtExceptionHandler,通过调用Thread.setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)方法,这是Thread的一个static方法。

如下:

[java]  view plain copy
  1. package com.exception;  
  2.   
  3. import java.lang.Thread.UncaughtExceptionHandler;  
  4.   
  5. public class WitchCaughtThread  
  6. {  
  7.     public static void main(String args[])  
  8.     {  
  9.         Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());  
  10.         Thread thread = new Thread(new Task());  
  11.         thread.start();  
  12.     }  
  13. }  
  14.   
  15. class ExceptionHandler implements UncaughtExceptionHandler  
  16. {  
  17.     @Override  
  18.     public void uncaughtException(Thread t, Throwable e)  
  19.     {  
  20.         System.out.println("==Exception: "+e.getMessage());  
  21.     }  
  22. }  

运行结果:

[plain]  view plain copy
  1. 1  
  2. ==Exception: / by zero  

如果采用线程池通过execute的方法去捕获异常,先看下面的例子:

[java]  view plain copy
  1. public class ExecuteCaught  
  2. {  
  3.     public static void main(String[] args)  
  4.     {  
  5.         ExecutorService exec = Executors.newCachedThreadPool();  
  6.         Thread thread = new Thread(new Task());  
  7.         thread.setUncaughtExceptionHandler(new ExceptionHandler());  
  8.         exec.execute(thread);  
  9.         exec.shutdown();  
  10.     }  
  11. }  
ExceptionHandler可参考上面的例子,运行结果:

[plain]  view plain copy
  1. 1  
  2. Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero  
  3.     at com.exception.Task.run(NoCaughtThread.java:25)  
  4.     at java.lang.Thread.run(Unknown Source)  
  5.     at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)  
  6.     at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)  
  7.     at java.lang.Thread.run(Unknown Source)  
可以看到并未捕获到异常。

这时需要将异常的捕获封装到Runnable或者Callable中,如下所示:

[java]  view plain copy
  1. package com.exception;  
  2.   
  3. import java.util.concurrent.ExecutorService;  
  4. import java.util.concurrent.Executors;  
  5.   
  6. public class ExecuteCaught  
  7. {  
  8.     public static void main(String[] args)  
  9.     {  
  10.         ExecutorService exec = Executors.newCachedThreadPool();  
  11.         exec.execute(new ThreadPoolTask());  
  12.         exec.shutdown();  
  13.     }  
  14. }  
  15.   
  16. class ThreadPoolTask implements Runnable  
  17. {  
  18.     @Override  
  19.     public void run()  
  20.     {  
  21.         Thread.currentThread().setUncaughtExceptionHandler(new ExceptionHandler());  
  22.         System.out.println(3/2);  
  23.         System.out.println(3/0);  
  24.         System.out.println(3/1);  
  25.     }  
  26. }  

运行结果:

[plain]  view plain copy
  1. 1  
  2. ==Exception: / by zero  
只有通过execute提交的任务,才能将它抛出的异常交给UncaughtExceptionHandler,而通过submit提交的任务,无论是抛出的未检测异常还是已检查异常,都将被认为是任务返回状态的一部分。如果一个由submit提交的任务由于抛出了异常而结束,那么这个异常将被Future.get封装在ExecutionException中重新抛出。
下面两个例子:

[java]  view plain copy
  1. package com.exception;  
  2.   
  3. import java.util.concurrent.ExecutorService;  
  4. import java.util.concurrent.Executors;  
  5.   
  6. public class SubmitCaught  
  7. {  
  8.     public static void main(String[] args)  
  9.     {  
  10.         ExecutorService exec = Executors.newCachedThreadPool();  
  11.         exec.submit(new Task());  
  12.         exec.shutdown();  
  13.     }  
  14. }  
[java]  view plain copy
  1. package com.exception;  
  2.   
  3. import java.util.concurrent.ExecutorService;  
  4. import java.util.concurrent.Executors;  
  5.   
  6. public class SubmitCaught  
  7. {  
  8.     public static void main(String[] args)  
  9.     {  
  10.         ExecutorService exec = Executors.newCachedThreadPool();  
  11.         exec.submit(new ThreadPoolTask());  
  12.         exec.shutdown();  
  13.     }  
  14. }  
运行结果都是:

[plain]  view plain copy
  1. 1  
这样可以证实我的观点。接下来通过这个例子可以看到捕获的异常:
[java]  view plain copy
  1. package com.exception;  
  2.   
  3. import java.util.concurrent.ExecutionException;  
  4. import java.util.concurrent.ExecutorService;  
  5. import java.util.concurrent.Executors;  
  6. import java.util.concurrent.Future;  
  7.   
  8. public class SubmitCaught  
  9. {  
  10.     public static void main(String[] args)  
  11.     {  
  12.         ExecutorService exec = Executors.newCachedThreadPool();  
  13.         Future<?> future = exec.submit(new Task());  
  14.         exec.shutdown();  
  15.         try  
  16.         {  
  17.             future.get();  
  18.         }  
  19.         catch (InterruptedException | ExecutionException e)  
  20.         {  
  21.             System.out.println("==Exception: "+e.getMessage());  
  22.         }  
  23.     }  
  24. }  
运行结果:

[plain]  view plain copy
  1. 1  
  2. ==Exception: java.lang.ArithmeticException: / by zero  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值