vertx的Future设计
异步痛点
1.回调地狱(CallBack hell) ; 解决方式 Promise 或 Future
2.执行异步后的结果如何回调currentThread ; 解决方式 Context 设计
3.如何处理依赖多异步的result进行逻辑 ; 解决方案 CompositeFuture
JDK的lib库 Callable和Future 问题
Callable任务可以返回结果,返回的结果可以由Future对象取出,但是调用Future.get()会阻塞当前线程
public V get() throws InterruptedException, ExecutionException {
int s = state;
if (s <= COMPLETING)
s = awaitDone(false, 0L);
return report(s);
}
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
if (unit == null)
throw new NullPointerException();
int s = state;
if (s <= COMPLETING &&
(s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
throw new TimeoutException();
return report(s);
}
/**
* 等待完成,或者中断、超时
*
* @param timed 定义了超时则为true
* @param nanos 等待时间
*/
private int awaitDone(boolean timed, long nanos)
throws InterruptedException {
final long deadline = timed ? System.nanoTime() + nanos : 0L;
WaitNode q = null;
boolean queued = false;
//轮询查看FutureTask的状态
for (;;) {
if (Thread.interrupted()) {//线程中断
removeWaiter(q);
throw new InterruptedException();
}
int s = state;
if (s > COMPLETING) {//完成或取消状态
if (q != null)
q.thread = null;
return s;
}
else if (s == COMPLETING)//正在set result,Thread “运行状态”进入到“就绪状态”
Thread.yield();
else if (q == null)
q = new WaitNode();
else if (!queued)
queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
q.next = waiters, q);
else if (timed) {
nanos = deadline - System.nanoTime();
if (nanos <= 0L) {
removeWaiter(q);
return state;
}
LockSupport.parkNanos(this, nanos);
}
else
LockSupport.park(this);
}
}
vertx的Future设计
1. Future通过事件注册(EventHandler)回调方式,来解决Thread阻塞问题.
UML图:
Futrue instances 采用FutureFactory生产,基于 SPI 机制:
public class FutureFactoryImpl implements FutureFactory {
private static final SucceededFuture EMPTY = new SucceededFuture<>(null);
/**
* 创建FutureImpl 实例
*/
public <T> Future<T> future() {
return new FutureImpl<>();
}
/**
* 返回一个常量 SucceededFuture 实例
* result本身为null, 可以减少内存开销
*/
public <T> Future<T> succeededFuture() {
@SuppressWarnings("unchecked")
Future<T> fut = EMPTY;
return fut;
}
/**
* 创建一个 SucceededFuture 实例
*/
public <T> Future<T> succeededFuture(T result) {
return new SucceededFuture<>(result);
}
/**
* 创建一个 FailedFuture 实例
*/
public <T> Future<T> failedFuture(Throwable t) {
return new FailedFuture<>(t);
}
/**
* 创建一个 FailedFuture 实例
*/
public <T> Future<T> failureFuture(String failureMessage) {
return new FailedFuture<>(failureMessage);
}
}
多异步的result如何组合(并行变串行)
使用的CompositeFuture,来处理多异步结果组合问题:采用计数器(Counters)的方法来解决 wait 问题
public class CompositeFutureImpl implements CompositeFuture, Handler<AsyncResult<CompositeFuture>> {
private final Future[] results;//定义数组
private int count;//计数器
private boolean completed;//是否完成
private Throwable cause;//错误原因
private Handler<AsyncResult<CompositeFuture>> handler;// 回调 eventHandler
public static CompositeFuture all(Future<?>... results) {
CompositeFutureImpl composite = new CompositeFutureImpl(results);//创建实例
int len = results.length; //获取 futures数组长度
for (int i = ; i < len; i++) {
results[i].setHandler(ar -> {
Handler<AsyncResult<CompositeFuture>> handler = null;
if (ar.succeeded()) {
synchronized (composite) { //添加内存屏障,防止并发问题
composite.count++;
if (!composite.isComplete() && composite.count == len) {//所有future成功
handler = composite.setCompleted(null);
}
}
} else {
synchronized (composite) {//添加内存屏障,防止并发问题
if (!composite.isComplete()) {//任何一个失败就失败
handler = composite.setCompleted(ar.cause());
}
}
}
if (handler != null) {//执行回调EventHandler
handler.handle(composite);
}
});
}
if (len == ) {//判断临界点
composite.setCompleted(null);
}
return composite;
}
}
public static CompositeFuture any(Future<?>... results) {
CompositeFutureImpl composite = new CompositeFutureImpl(results);
int len = results.length;
for (int i = ;i < len;i++) {
results[i].setHandler(ar -> {
Handler<AsyncResult<CompositeFuture>> handler = null;
if (ar.succeeded()) {
synchronized (composite) {
if (!composite.isComplete()) {//任何一个成功
handler = composite.setCompleted(null);
}
}
} else {
synchronized (composite) {
composite.count++;
if (!composite.isComplete() && composite.count == len) {//所有future失败
handler = composite.setCompleted(ar.cause());
}
}
}
if (handler != null) {//执行回调EventHandler
handler.handle(composite);
}
});
}
if (results.length == ) {//判断临界点
composite.setCompleted(null);
}
return composite;
}
private static CompositeFuture join(Function<CompositeFuture, Throwable> pred, Future<?>... results) {
CompositeFutureImpl composite = new CompositeFutureImpl(results);
int len = results.length;
for (int i = ; i < len; i++) {
results[i].setHandler(ar -> {
Handler<AsyncResult<CompositeFuture>> handler = null;
synchronized (composite) {
composite.count++;
if (!composite.isComplete() && composite.count == len) {//处理所有不管失败还是成功
// Take decision here
Throwable failure = pred.apply(composite);
handler = composite.setCompleted(failure);
}
}
if (handler != null) {
handler.handle(composite);
}
});
}
if (len == ) {//{//判断临界点
composite.setCompleted(null);
}
return composite;
}
/**
* 根据下标返回结果
* /
public <T> T resultAt(int index) {
return this.<T>future(index).result();
}
public interface CompositeFuture extends Future<CompositeFuture> {
/**
* 返回list Future.result()
*/
default <T> List<T> list() {
int size = size();
ArrayList<T> list = new ArrayList<>(size);
for (int index = ;index < size;index++) {
list.add(resultAt(index));
}
return list;
}
}
vertx的Future设计的更多相关文章
- 多线程手写Future模式
future模式 在进行耗时操作的时候,线程直接阻塞,我们需要优化这样的代码,让他再启动一个线程,不阻塞.可以执行下面的代码. 这个时候我们就用到了未来者模式 future设计类 只有一个方法 pub ...
- vertx的ShardData共享数据
数据类型 一共4种 synchronous shared maps (local) asynchronous maps (local or cluster-wide) asynchronous loc ...
- vertx模块DeploymentManager部署管理器
DeploymentManager public DeploymentManager(VertxInternal vertx) { this.vertx = vertx; loadVerticleFa ...
- vertx读取配置文件,获得端口号
1:在src/conf目录下创建conf.json { } 2:创建Verticle, config().getInteger("http.port", 8080),将会读取配置文 ...
- 从浏览器输入参数,到后台处理的vertx程序
vertx由于性能较高,逐渐变得流行.下面将一个vertx的入门案例. 添加依赖 <!-- vertx --> <dependency> <groupId>io.v ...
- vertx连接mysql数据库
1:创建一个verticle组件 package jdbcConnection; import io.vertx.core.AbstractVerticle; import io.vertx.core ...
- Netty核心概念(9)之Future
1.前言 第7节讲解JAVA的线程模型中就说到了Future,并解释了为什么可以主线程可以获得线程池任务的执行后结果,变成一种同步状态.秘密就在于Java将所有的runnable和callable任务 ...
- Java网络编程中异步编程的理解
目录 前言 一.异步,同步,阻塞和非阻塞的理解 二.异步编程从用户层面和框架层面不同角度的理解 用户角度的理解 框架角度的理解 三.为什么使用异步 四.理解这些能在实际中的应用 六.困惑 参考文章 前 ...
- Vert.x Core 文档手册
Vert.x Core 文档手册 中英对照表 Client:客户端 Server:服务器 Primitive:基本(描述类型) Writing:编写(有些地方译为开发) Fluent:流式的 Reac ...
随机推荐
- 了解Vue.js
一.了解Vue (1)Vue.js在设计上采用MVVM(Model-View-ViewModel)模式 当View变化时,会自动更新到ViewModel,反之亦然.View与ViewModel通过双向 ...
- leanote使用本地账户时,去掉待同步的小红点
切换开发者工具,如下图,点击左上角的箭头图标,选取元素,直接选择小红点. 然后会看到小红点来自于resources/app/public/themes/default.css文件中2092行: .it ...
- Luogu4494 [HAOI2018]反色游戏 【割顶】
首先发现对于一个联通块有奇数个黑点,那么总体来说答案无解.这个很容易想,因为对每个边进行操作会同时改变两个点的颜色,异或值不变. 然后一个朴素的想法是写出异或方程进行高斯消元. 可以发现高斯消元的过程 ...
- app Inventor
什么是App Inventor ? MIT 官方网站 http://ai2.appinventor.mit.edu/Ya_tos_form.html 广州中文镜像网站 http://app.gzjk ...
- Jdk和Spring Boot版本选择
==========================版本选择的原则:==========================1. 优先选择官方指定的long-term support(LTS)版本, 非L ...
- 记一次线上Java程序导致服务器CPU占用率过高的问题排除过程
博文转至:http://www.jianshu.com/p/3667157d63bb,转本博文的目的就是需要的时候以防忘记 1.故障现象 客服同事反馈平台系统运行缓慢,网页卡顿严重,多次重启系统后问题 ...
- Koa与Node.js开发实战(1)——Koa安装搭建(视频演示)
学习架构: 由于Koa2已经支持ES6及更高版本,包括支持async方法,所以请读者保证Node.js版本在7.6.0以上.如果需要在低于7.6的版本中应用Koa的async方法,建议使用Babel ...
- django-个人博客登录及权限验证功能的实现
完成注册后随即开始进行登录,登录后页面显示登录者的名称 实现如下: 前端页面html,对session进行判断,有值则显示登录者的名字 ,无值则显示注册字样: 后台views函数 首先对验证码进行验 ...
- docker学习------记录centos7.5下docker安装更换国内源的处理过程
一.centos7.5下更换阿里源 1.装好centos7.5镜像,将yum源更换为阿里源 第一步:刚出的centos7.5是解析不到阿里的东西的,所以找了台centos7.4,下载一些包 (1) 下 ...
- python中的图像数据库PIL
from PIL import Image im = Image.open("图片路径") im.function() 常用的函数: 1.im.crop(x,y,x1,y1) 对图 ...