completableFuture源码解析

简单解析image.png

首先尝试不看源码情况下讲清楚CompletableFuture. CompletableFuture主要由两个类组成,CompletableFuture与Completion,其中Completion有非常多实现类,像是一元的UniCompletion,二元的BiCompletion等,整体逻辑都是差不多的,这里以基于一元UniCompletion的UniApply来讲解.
cf1是被观察者,当cf1 result为null时候,这时候执行thenApply,会生成一个UniApply对象加入到cf1 stack中,当cf1 result有值以后,会执行stack中每一个Completion.

源码解析

uniApplyStage

//执行thenApply后调用此函数
private <V> CompletableFuture<V> uniApplyStage(
    Executor e, Function<? super T,? extends V> f) {
   
    if (f == null) throw new NullPointerException();
    Object r;
    //当前cf result不为空的话,不需要入栈,直接执行
    if ((r = result) != null)
        return uniApplyNow(r, e, f);
    CompletableFuture<V> d = newIncompleteFuture();
    //构建一个UniApply,入栈到当前cf的stack
    unipush(new UniApply<T,V>(e, d, this, f));
    return d;
}

postComplete

public boolean complete(T value) {
   
	//cas方式赋值result
    boolean triggered = completeValue(value);
    postComplete();
    return triggered;
}
final void postComplete() {
   
    CompletableFuture<?> f = this; Completion h;
    while ((h = f.stack) != null ||
           (f != this && (h = (f = this).stack) != null)) {
   
        CompletableFuture<?> d; Completion t;
        //f的stack由h替换成h.next
        if (STACK.compareAndSet(f, h, t = h.next)) {
   
            if (t 
  • 20
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值