Callable 源码解析

概述

这里Callable 的使用以 FutureTask 举例,源码示例如下

 	public static void main(String[] args) throws ClassNotFoundException, ExecutionException, InterruptedException {
        FutureTask futureTask = new FutureTask(new Callable() {
            @Override
            public Object call() throws Exception {
                return 1;
            }
        });
        new Thread(futureTask).start();
        System.out.println(futureTask.get());
    }

原理

Callable 接口

public interface Callable<V> {
    V call() throws Exception;
}

这个接口可以说是平平无奇,就只定义了一个方法

FutureTask

public class FutureTask<V> implements RunnableFuture<V> {...}
public interface RunnableFuture<V> extends Runnable, Future<V> {...}

这里可以发现 FutureTask 也是一个 Runnable,所以一定重写了run()方法

public void 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 {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            runner = null;
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

这里可以看到这个run()方法,就是执行到了callable 的 call(),返回的结果为 result
最后如果执行成功还会进行 set(result) ,下面就来看看这个方法

	protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }

这里我们看到使用cas 设置outcome 属性为 v ,这个 v 就是前面说的 result,
而outcome 则是FutureTask中的一个Object类型的属性,也就是说,FutureTask 在执行的时候,将结果保存在内部的一个Object属性中
所以,后续才能通过get()获得到这个结果

接下来我们在来看看 futureTask.get() 的get()方法,看看结果是不是如上面猜想的一样

	public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }
    //其他的不关注,进入report(s);
     private V report(int s) throws ExecutionException {
        Object x = outcome;
        if (s == NORMAL)
            return (V)x;
        if (s >= CANCELLED)
            throw new CancellationException();
        throw new ExecutionException((Throwable)x);
    }

可以看到当执行futureTask.get() 的时候,获取的就是 outcome,我们上面的猜想完全正确

总结

Callable其实就是将 run 方法里面执行的逻辑抽离出来,而执行的结果通过一个Object类型的属性(outcome)保存
,当我们获取执行结果的时候,并不知得到run()方法的返回值,而是取获取这个 Object 属性(outcome)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值