Callable异常封装
- Executor框架利用FutureTask来完成异步任务,并可以用来进行任何潜在的耗时计算,而且可以在真正需要计算结果之前就启动它们开始计算。
- 不能在构造函数或者静态初始化方法中启动线程并不是明智的举措,所以可以提供一个start()方法来启动线程(???为什么这样做)。
- Callable记录这些异步任务,可以抛出受检异常或者未受检异常,并且任何代码都可能抛出Error,无论执行任务的代码抛出什么,它都被封装成一个ExecutionException,并被Future.get()重新抛出。
- 如果Future.get()抛出CancellationException,则意味着异步任务取消或者失败,此时可以把执行异步任务失败的,如果是做缓存的或者其他的,可以将这些失败的,从其中移除
- 封装Callable的异常抛出类:
//抛出受检异常;RuntimeException;Error; 必须对这3中情况分别处理,在调用
lanunderThrowable之前,先检查自己已知异常,并重新抛出,只留出未受检异常,通过调用lanunderThrowable来处理他们,并且抛出未受检异常.如果Throwable向lanunderThrowable抛出一个Error,lanunderThrowable直接抛出;如果不是一个RuntimeException,会抛出IllegalStateExceltion;剩下的RuntimeException,
lanunderThrowable会把它返回给它调用者。
//Callable异常封装类,将运行时异常返给它调用者
package org.javabase.thread.latch;
/**
* StaticUtilities
*
* @author Brian Goetz and Tim Peierls
*/
public class LaunderThrowable {
/**
* {@link Throwable}强转为{@link RuntimeException}
* <p/>
* If the Throwable is an Error, throw it; if it is a
* RuntimeException return it, otherwise throw IllegalStateException
*/
public static RuntimeException launderThrowable(Throwable t) {
if (t instanceof RuntimeException)
return (RuntimeException) t;
else if (t instanceof Error)
throw (Error) t;
else
throw new IllegalStateException("Not unchecked", t);
}
}
//使用示例:
public ProductInfo get() throws DataLoadException, InterruptedException {
try {
return futureTask.get();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof DataLoadException)
throw (DataLoadException) cause;
else
throw LaunderThrowable.launderThrowable(cause);
}
}