Callable异常封装

Callable异常封装

  1. Executor框架利用FutureTask来完成异步任务,并可以用来进行任何潜在的耗时计算,而且可以在真正需要计算结果之前就启动它们开始计算。
  2. 不能在构造函数或者静态初始化方法中启动线程并不是明智的举措,所以可以提供一个start()方法来启动线程(???为什么这样做)。
  3. Callable记录这些异步任务,可以抛出受检异常或者未受检异常,并且任何代码都可能抛出Error,无论执行任务的代码抛出什么,它都被封装成一个ExecutionException,并被Future.get()重新抛出
  4. 如果Future.get()抛出CancellationException,则意味着异步任务取消或者失败,此时可以把执行异步任务失败的,如果是做缓存的或者其他的,可以将这些失败的,从其中移除
  5. 封装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);
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值