FutureTask 会 “吞掉“ 异常是怎么回事?需要注意些什么?

2023-10-10 06:40

本文主要是介绍FutureTask 会 “吞掉“ 异常是怎么回事?需要注意些什么?,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

这次 , 没有废话,切入正题!

Callable#call方法里,如果没有try-catch的情况下,如果call方法运行时,一旦出现异常,那么该异常会被Future所接收到,且只有调用 Future # get方法才会抛出。也就是说,如果你不调用get方法,做些异常处理的话,真的发现不了问题发生在哪?这种情况,就好像是异常被"吞掉" 了。

import java.util.concurrent.Callable;public class MyCallable implements Callable<String> {@Overridepublic String call() throws Exception {System.out.println("===> 开始执行callable");int i = 1 / 0; //异常的地方return "callable的结果";}
}
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;public class CallableAndRunnableTest {public static void main(String[] args) {System.out.println(" =========> main start ");ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100));Future<String> submit = threadPoolExecutor.submit(new MyCallable());try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(" =========> main end ");}
}

运行结果:

 =========> main start ===> 开始执行callable=========> main end 

懵逼了,竟然那么大的异常,都没有发现。试试Runnable 会怎样呢,

public class MyRunnable implements Runnable {@Overridepublic void run() {System.out.println("====》 开始执行runnable ");int i = 1 / 0; //异常的地方}
}
=========> main start 
====》 开始执行runnable 
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zeroat com.yuki.test.thread.MyRunnable.run(MyRunnable.java:7)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)=========> main end 

看来Runnable很符合我们的胃口嘛,要的就是异常给我抛出来 。这样不用挠头找Bug的根源在哪了啊。

回过头,看看Callable 怎么就把异常“吞掉”了呢?答案就在源码里,别着急,慢慢找哈。

先进入 threadPoolExecutor.submit(new MyCallable()) 的源码 ,跳转到了 AbstractExecutorService

 /*** @throws RejectedExecutionException {@inheritDoc}* @throws NullPointerException       {@inheritDoc}*/public <T> Future<T> submit(Callable<T> task) {if (task == null) throw new NullPointerException();//把Callable赋值给FutureTask,这行代码,我是不是可以理解成把对象封装成FutureTask对象RunnableFuture<T> ftask = newTaskFor(task);execute(ftask);return ftask;}

接着,进入newTaskFor(task) 看看干了些啥事情吧~ 最后跟踪到FutureTask.java 的构造方法来了。

   public FutureTask(Callable<V> callable) {if (callable == null)throw new NullPointerException();this.callable = callable;this.state = NEW;       // ensure visibility of callable}

看上去,好像就是FutureTask的成员变量初始化,对吧? 一个Callable ,一个是状态标识(zhi)。那回到前面,FutrueTask 可以直接赋值给 RunableFuture<T> ? 那估计是个接口,看看源码确认下:

public interface RunnableFuture<V> extends Runnable, Future<V> {/*** Sets this Future to the result of its computation* unless it has been cancelled.*/void run();
}

意料之中啊, RunableFuture<T> 就是个接口,等等,发现它继承了Runnable 接口 , 那这里就必须要看下 FutureTask 里的run方法 是不是和 构造时的Callable 有关系呢 ?所以 FutureTask 的run方法,必须要看下了。记得,重点关注怎么把异常吞掉了的?

 public void run() {// 状态不属于初始状态的情况下,不进行后续逻辑处理// 那也就是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 {// 执行 Callable 里的 call 方法 ,将结果存入result变量中result = c.call();ran = true;} catch (Throwable ex) {result = null;ran = false;// call 方法异常 , 记录下异常结果setException(ex);}// call 方法正常执行完毕 ,进行结果存储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 interruptsint s = state;if (s >= INTERRUPTING)handlePossibleCancellationInterrupt(s);}}

接下去,就要重点关注,如果存储正常结果set(result)setException(ex) 的了。

 protected void setException(Throwable t) {if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {outcome = t;UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final statefinishCompletion();}}protected void set(V v) {if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {outcome = v;UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final statefinishCompletion();}}

这两个方法 ,乍一眼还以为一样的代码呢? 都做了一个操作,就是将正常结果result 和 异常结果 exception 都赋值给了 outcome 这个变量 。

  /** The result to return or exception to throw from get() */private Object outcome; // non-volatile, protected by state reads/writes

其它的几个步骤,就是更新下 Task 的状态 ,以及通知其它的等待线程,告诉它们,当前这个Task 已经完成了。

这里有必须看下Task的结束时的状态,如果正常结束,状态为 NORMAL , 异常结果,状态为EXCEPTIONAL 。 看下几个状态的定义,如下:

  private volatile int state;private static final int NEW          = 0;private static final int COMPLETING   = 1;private static final int NORMAL       = 2;private static final int EXCEPTIONAL  = 3;private static final int CANCELLED    = 4;private static final int INTERRUPTING = 5;private static final int INTERRUPTED  = 6;

好了,到这里,就大概看完了FutureTask#run 方法的实现了。

这里,我们停一下,快接近答案了,回忆下,我们是不是通过Future#get 方法获取到结果的,所以现在只要研究下get方法。 由于FutureTask 还实现了 Future 接口,在这个接口里就定义了 get 方法。

在这里插入图片描述
翻阅FutureTask#get

 /*** @throws CancellationException {@inheritDoc}*/public V get() throws InterruptedException, ExecutionException {int s = state;// NORMAL(2) 、EXCEPTIONAL(3) 都大于 COMPLETING(1),所以Task结束之后,不会走该ifif (s <= COMPLETING)s = awaitDone(false, 0L);// 重点: 返回结果return report(s);}private V report(int s) throws ExecutionException {// 之前正常结果或者异常都存放在Object outcomme 中了Object x = outcome;// 正常返回if (s == NORMAL)return (V)x;// EXCEPTIONAL(3) 小于 CANCELLED(4) ,所以不会走该if分支,直接后续的throw 抛异常的逻辑if (s >= CANCELLED)throw new CancellationException();// 不等于NORMAL 且 大于等于 CANCELLED  ,  再结合 调用 report(int s ) 之前也做了state 的过滤//到这一步,那只能是EXCEPTIONAL(3) throw new ExecutionException((Throwable)x);}

哇塞 ,终于找到了答案,给自己鼓个掌 !!!

总结:

  • submit(Callable callable ) 其实就是通过FutureTask 对 Callable#call 进行一层try-catch 操作,正常或者异常的执行结果都存入到FutureObject outcome 内部成员变量中 。 在FutureTask#get获取执行结果的时候,依据内部执行状态标识来选择以哪种方式返回outcome , 如果是NORMAL 状态 ,就直接返回接口 ,如果是EXCEPTIONAL 状态 就 以throw ExecutionException 的方式返回。
  • FutureTask#get方法是一个阻塞方法,可以自行从上面贴出源码找答案。
  • 不论Runnable#run() 还是Callable#call() 方法 , 都是普通方法,那为啥感觉有点与众不同?emm… 拿Runnable 来说,主要是因为和Thread 挂钩,实现了线程的执行方法体。如果不看Thread ,不也就只是个接口的定义方法嘛?
  • 如果你不想调用FutureTask#get 方法 , 建议使用Runnable 或者 在Callable的call方法自行try-catch一把。
public class MyCallable implements Callable<String> {@Overridepublic String call() throws Exception {try{System.out.println("===> 开始执行callable");int i = 1 / 0; //异常的地方}catch(Exception e){//异常处理System.out.println("===> 糟啦 , callable 执行异常: ");}       return "callable的结果";}
}

这篇关于FutureTask 会 “吞掉“ 异常是怎么回事?需要注意些什么?的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/178685

相关文章

Java异常架构Exception(异常)详解

《Java异常架构Exception(异常)详解》:本文主要介绍Java异常架构Exception(异常),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1. Exception 类的概述Exception的分类2. 受检异常(Checked Exception)

Java报NoClassDefFoundError异常的原因及解决

《Java报NoClassDefFoundError异常的原因及解决》在Java开发过程中,java.lang.NoClassDefFoundError是一个令人头疼的运行时错误,本文将深入探讨这一问... 目录一、问题分析二、报错原因三、解决思路四、常见场景及原因五、深入解决思路六、预http://www

一文带你深入了解Python中的GeneratorExit异常处理

《一文带你深入了解Python中的GeneratorExit异常处理》GeneratorExit是Python内置的异常,当生成器或协程被强制关闭时,Python解释器会向其发送这个异常,下面我们来看... 目录GeneratorExit:协程世界的死亡通知书什么是GeneratorExit实际中的问题案例

Java捕获ThreadPoolExecutor内部线程异常的四种方法

《Java捕获ThreadPoolExecutor内部线程异常的四种方法》这篇文章主要为大家详细介绍了Java捕获ThreadPoolExecutor内部线程异常的四种方法,文中的示例代码讲解详细,感... 目录方案 1方案 2方案 3方案 4结论方案 1使用 execute + try-catch 记录

Java8需要知道的4个函数式接口简单教程

《Java8需要知道的4个函数式接口简单教程》:本文主要介绍Java8中引入的函数式接口,包括Consumer、Supplier、Predicate和Function,以及它们的用法和特点,文中... 目录什么是函数是接口?Consumer接口定义核心特点注意事项常见用法1.基本用法2.结合andThen链

解决java.lang.NullPointerException问题(空指针异常)

《解决java.lang.NullPointerException问题(空指针异常)》本文详细介绍了Java中的NullPointerException异常及其常见原因,包括对象引用为null、数组元... 目录Java.lang.NullPointerException(空指针异常)NullPointer

Spring Boot统一异常拦截实践指南(最新推荐)

《SpringBoot统一异常拦截实践指南(最新推荐)》本文介绍了SpringBoot中统一异常处理的重要性及实现方案,包括使用`@ControllerAdvice`和`@ExceptionHand... 目录Spring Boot统一异常拦截实践指南一、为什么需要统一异常处理二、核心实现方案1. 基础组件

Python中异常类型ValueError使用方法与场景

《Python中异常类型ValueError使用方法与场景》:本文主要介绍Python中的ValueError异常类型,它在处理不合适的值时抛出,并提供如何有效使用ValueError的建议,文中... 目录前言什么是 ValueError?什么时候会用到 ValueError?场景 1: 转换数据类型场景

Spring中Bean有关NullPointerException异常的原因分析

《Spring中Bean有关NullPointerException异常的原因分析》在Spring中使用@Autowired注解注入的bean不能在静态上下文中访问,否则会导致NullPointerE... 目录Spring中Bean有关NullPointerException异常的原因问题描述解决方案总结

Python中的异步:async 和 await以及操作中的事件循环、回调和异常

《Python中的异步:async和await以及操作中的事件循环、回调和异常》在现代编程中,异步操作在处理I/O密集型任务时,可以显著提高程序的性能和响应速度,Python提供了asyn... 目录引言什么是异步操作?python 中的异步编程基础async 和 await 关键字asyncio 模块理论