本文主要是介绍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 操作,正常或者异常的执行结果都存入到Future
的Object 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 会 “吞掉“ 异常是怎么回事?需要注意些什么?的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!