Java propernableFuture.Complete()块

技术标签: java.  多线程  未来  反应堆  完整的未来

在Java中使用的完成文件时,我遇到了问题。我有2个选择请求,在从服务器接收响应时填写。

在连接线程(线程1)(使用反应器)中,我使用:

if(hasException) {
   selectFuture.completeExceptionally(new ClientException(errorCode));
} else {
   System.out.println("Before complete future");
   selectFuture.complete(result);
   System.out.println("After complete future");
}

在其他线程(线程2)中,我使用:

CompleteFuture.allOf(allSelect).whenComplete((aVoid, throwable) -> {
   System.out.println("Receive all future");
   // Do sth here
});

我的情况是系统打印出“收到所有未来”,但在呼叫时被阻止了线程1 future.complete(result); 它无法摆脱该命令。如果在线程2中,我使用 CompletableFuture.allOf(allOfSelect).get(),线程1将正确运行。但是使用 CompletableFuture.get() 减少性能,所以我想使用 CompletableFuture.whenComplete().

任何人都可以帮助我解释阻止的原因?

谢谢!

看答案

complete 呼叫触发所有依赖 CompletionStages。

所以,如果你以前注册了一个 BiConsumerwhenComplete, 这 complete 将在其调用线程中调用它。在您的情况下,呼叫 complete 会返回什么时候 BiConsumer 你经过 whenComplete 完成。这是描述的 javadoc类

可以执行为依赖非异步方法提供的操作 完成当前的线程 CompletableFuture,或通过完成方法的任何其他呼叫者。

(另一个来电者 是相反的情况,线程呼叫 whenComplete 实际上会适用 BiConsumer 如果 目标 CompletableFuture 已经完成了。)

这是一个小程序来说明行为:

public static void main(String[] args) throws Exception {
    CompletableFuture<String> future = new CompletableFuture<String>();
    future.whenComplete((r, t) -> {
        System.out.println("before sleep, executed in thread " + Thread.currentThread());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("after sleep, executed in thread " + Thread.currentThread());
    });

    System.out.println(Thread.currentThread());
    future.complete("completed");
    System.out.println("done");
}

这将打印

Thread[main,5,main]
before sleep, executed in thread Thread[main,5,main]
after sleep, executed in thread Thread[main,5,main]
done

表明这一点 BiConsumer 应用于主线程,称为那个 complete.

您可以使用 whenCompleteAsync 强迫执行 BiConsumer 在一个单独的线程中。

执行给定行动的[...] 使用此阶段的默认异步执行设施在此阶段完成时.

例如,

public static void main(String[] args) throws Exception {
    CompletableFuture<String> future = new CompletableFuture<String>();
    CompletableFuture<?> done = future.whenCompleteAsync((r, t) -> {
        System.out.println("before sleep, executed in thread " + Thread.currentThread());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("after sleep, executed in thread " + Thread.currentThread());
    });

    System.out.println(Thread.currentThread());
    future.complete("completed");
    System.out.println("done");
    done.get();
}

将打印

Thread[main,5,main]
done
before sleep, executed in thread Thread[ForkJoinPool.commonPool-worker-1,5,main]
after sleep, executed in thread Thread[ForkJoinPool.commonPool-worker-1,5,main]

表明这一点 BiConsumer 应用于单独的线程。


智能推荐

JAVA --- 初始化块

Java  ---  初始化块        初始化块和构造器的功能很相似,都可以对Java对象进行初始化操作,从而使Java对象的信息更加完整。        一个类里可以有多个初始化块,初始化块是按照定义的先后顺序执行,(尽量使用一个初始化块,初始化块是隐式执行且全部执行,合并成一个初始化块可以...

Java-代码块,继承

一.代码块 (1)分类 局部代码块 在方法中出现;限定变量生命周期,及早释放,提高内存利用率 构造代码块 在类中方法外出现;多个构造方法方法中相同的代码存放到一起 静态代码块 在类中方法外出现,并加上static修饰;用于给类进行初始化,在加载的时候就执行,并且只执行一次。 (2)案例演示 public class lalala { static { System.out.println (&ld...

Java初始化块

撰写时间:2019年04月18日 Java初始化块根据有无static修饰分为两类: 1、无static修饰的:初始化块 2、有static修饰的:静态初始化块 作用:初始化数据 初始化块跟构造器相似,初始化块相当于构造器的补充,用于创建对象是给对象的初始 化,不同的是初始化块比构造器多个优势是——先执行。 我们可能有四五个构造器,如果每个构造器都要写一遍就重复了,这时候我...

JAVA初始化块

开发工具与关键技术:MyEclipse 10 JAVA 作者:黄冠棋 撰写时间:2019年04月17日 初始化块根据是否使用static修饰分为两类: 不使用static修饰的是初始化块 使用static修饰的是静态初始化块 初始化块相当于是对构造器的补充,用于创建对象时给对象的初始化,在构 造器之前执行 静态初始化块用static修饰,又叫类初始化块 静态初始化块负责对类进行初始化,因此类初始化...

Java 同步代码块synchronized

如何使用synchronized  synchronized 关键字​ 同步代码块 synchronized 原理浅析 如何使用Java同步代码块synchronized  2018年拍摄于日本奈良的小鹿,鹿随便摸,手感棒棒的。 微信公众号 王皓的GitHub:https://github.com/TenaciousDWang   上回说到线程的生命周期,今...

猜你喜欢

java 初始化块

class Bike8{       int speed;              Bike8(){System.out.println("constructor is ...

原型对象,原型链

函数都有prototype属性,它指向原型对象。 实例对象有__proto__属性,它指向对象原型 每一个原型对象都有constructor输赢,指向构造函数,每一个原型对象又具有__proto__属性,这个指向Object.prototype.在这里插入图片描述...

Node 调用 dubbo 服务的探索及实践

2.Dubbo简介 2.1 什么是dubbo Dubbo是一款高性能、轻量级的开源Java RPC框架,它提供了三大核心能力:面向接口的远程方法调用,智能容错和负载均衡,以及服务自动注册和发现。 2.2 流程图 Provider : 暴露服务的服务提供方。 Consumer : 调用远程服务的服务消费方。 Registry : 服务注册与发现的注册中心。 Monito...

mysql总结

mysql基础入门的总结     关于数据库:     数据库是软件开发人员要掌握的基本工具,软件的运行的过程就是操作数据的过程,数据库中的数据无非就是几个操作:增-删-查-改。         Mysql安装完成后,需要配置变量环境,找到配置路径path,然后把mysql安装目录bin文件导入就可以了。 然后运行cm...

adb及monkey常用命令

adb常用命令: 查看手机是否连接:adb devices   连接设备:adb connect 设备ip:端口号  若有连接多个设备需指明设备ip及端口号 安装APP:adb install [-r] 包名  -r表示覆盖安装,首次安装可省略 卸载APP:adb uninstall 包名 列出设备中所有应用包名:adb shell pm list packages ...

问答精选

Correctly formatting GCM notifications?

I'm currently trying out the google cloud messaging service with its sample application "Guestbook." https://developers.google.com/cloud/samples/mbs/ I'm attempting to send notifications tha...

Are there any performance benefits of using Asynchronous functions over Synchronous in Node Js?

Now I came across an article that distinguishes between an Asynchronous function and Synchronous functions. From my understanding of the different examples and explanations, synchronous functions are ...

Python: Costing calculator output

Good day all I'm busy creating a small costing calculator for the signage department. I'm not getting the calculator to output the amount. Brief Description: You enter the height and width and then wh...

Flask-SQLAlchemy - model has no attribute 'foreign_keys'

I have 3 models created with Flask-SQLalchemy: User, Role, UserRole role.py: user.py: user_role.py: If I try (in the console) to get all users via User.query.all() I get AttributeError: 'NoneType' obj...

Seeding many PRNGs, then having to seed them again, what is a good quality approach?

I have many particles that follow an stochastic process in parallel. For each particle, there is a PRNG associated to it. The simulation must go through many repetitions to get average results. For ea...

相关问题

相关文章

热门文章

推荐文章

相关标签

推荐问答