Java 8 CompletableFuture思考

最近一直在用响应式编程写Java代码,用的框架大概上有WebFlux(Spring)、R2dbcAkka...一些响应式的框架。

全都是Java写的,我于是就在想:

全都是Java的代码怎么搞成了响应式呢? 是不是语言本身就支持呢?

于是找到了Java 8 的 concurrency。这个是啥呢?

写个代码看一下:

@Test
void test7() throws ExecutionException, InterruptedException {
CompletableFuture<String> future = new CompletableFuture<>();
Runnable task = new Runnable() {
@Override
public void run() {
try {
String result = "result";
future.complete(result);
} catch (Exception e) {
future.completeExceptionally(e);
}
}
};
//这里是new了一个新的线程去跑
final Thread thread = new Thread(task);
thread.start();
final String s = future.get();
assertEquals("result", s);
}

代码写到了这里,感觉和JS的Promise如出一辙呀:

it('just a promise test', function () {
Promise.resolve('success'); // return promise
Promise.reject('error'); // return promise
new Promise((resolve, reject) => {
resolve('success');
reject('error');
});
});

ForkJoinPool玩一把

@Test
void test8() throws ExecutionException, InterruptedException {
CompletableFuture<String> future = new CompletableFuture<>();
final Runnable runnable = () -> {
try {
String result = "result";
future.complete(result);
} catch (Exception e) {
future.completeExceptionally(e);
}
}; ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
forkJoinPool.submit(runnable);
final String s = future.get();
assertEquals("result", s);
}

写到了这里,我感觉我大概明白了所用的响应式框架里边怎么玩的了。


假设说不用框架纯Java的代码怎么写那些响应式代码呢?

比如说常用的操作符map,zip,reduce,group...这些要怎么玩?

@Test
void test9() throws ExecutionException, InterruptedException, TimeoutException {
CompletableFuture<String> future = new CompletableFuture<>();
final Runnable runnable1 = () -> {
try {
String result = "1";
future.complete(result);
} catch (Exception e) {
future.completeExceptionally(e);
}
}; CompletableFuture<String> future2 = new CompletableFuture<>();
final Runnable runnable2 = () -> {
try {
String result = "2";
future2.complete(result);
} catch (Exception e) {
future2.completeExceptionally(e);
}
}; ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
forkJoinPool.submit(runnable1);
forkJoinPool.submit(runnable2);
final List<Integer> result = future
.whenComplete((aVoid, throwable) -> {
if (Objects.nonNull(throwable)) {
log.error("bla bla bla,", throwable);
} })
.thenApply(s -> Integer.parseInt(s)) // like stream Map
.thenCombine(future2, (integer, s) -> Arrays.asList(integer, Integer.parseInt(s)))// zip
.thenCompose(list -> CompletableFuture.completedFuture(list)) // flatMap or mapAsync
.get(3, TimeUnit.SECONDS);
assertThat(result)
.containsExactly(1, 2);
}

这些.thenXXX方法都是可以换成.thenXXXAsync的,之间的不同就是换成另一个线程去处理,而不是当前线程继续处理。

如何做reduce,collect,groupBy,orderBy操作呢?

答案:.thenComposeor.thenApply方法

@Test
void test10() throws ExecutionException, InterruptedException, TimeoutException {
CompletableFuture<List<Integer>> future = new CompletableFuture<>();
final Runnable runnable1 = () -> {
try {
future.complete(Arrays.asList(1, 3, 5));
} catch (Exception e) {
future.completeExceptionally(e);
}
};
ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
forkJoinPool.submit(runnable1);
final Integer result = future
.thenCompose(list -> CompletableFuture.completedFuture(list.stream().reduce(0, Integer::sum)))
.get(3, TimeUnit.SECONDS);
assertThat(result).isEqualTo(3);
}

有没有类似于Promise.all和Promise.race之类的方法呢?

答案是有的CompletableFuture.allOf(futures...)CompletableFuture.anyOf(futures...)

总结

断断续续思考了两天,心中的困惑才一点点的解开,有深度的思考是不可缺少的。

source

https://github.com/1483523635/blogs/blob/master/java/basic/future.md

Java 8 CompletableFuture思考的更多相关文章

  1. 关于Java 项目的思考总结

    Java 项目思考总结 前言 今天是2017年3月25日,笔者已经毕业半年,工作经验一年. 正好有心思写这个总结. 持续开发 对于Java项目,我所接触的一般就是JavaWeb项目和 Java Jar ...

  2. Java异步CompletableFuture的使用

    所谓异步调用其实就是实现一个可无需等待被调用函数的返回值而让操作继续运行的方法.Java中的CompletableFuture 提供了四个静态方法来创建一个异步操作. public static Co ...

  3. Java框架的思考

    目前的JAVA 企业级开发框架,我们常用的大致包括IOC AOP MVC ORM框架 1. IOC spring是一个非常棒的ico容器,其思想非常简单,用一个集合对象如MAP 来缓存对象(对象都是单 ...

  4. 关于java对象的思考

    不可变对象和类 由不可变类创建的对象就是不可变对象,要使一个类成为不可变的,它必须满足下面的需求: 所有数据域都是私有的 没有修改器方法 没有一个访问器的方法,它会返回一个指向可变数据域的引用 看下面 ...

  5. 对 Kotlin 与 Java 编程语言的思考

    从长远来看,排名前10的也基本上是Java.C.C++.Python.C#.VB.PHP.JavaScript.至于Kotlin的排名,11月份在编程语言仅排41名,Ratings仅有0.216%. ...

  6. 有 a - b < c 对Java安全性的思考

    软件工程中,不论使用哪种开发语言,安全性一直是一个非常棘手却又重要的问题.安全性是软件开发领域永远的主题之一,而且随着互联网的蜂拥发展而带动的新技术的兴起与革命(比如近几年火起来的node.js,py ...

  7. 【多线程】java多线程Completablefuture 详解【在spring cloud微服务之间调用,防止接口超时的应用】【未完成】

    参考地址:https://www.jianshu.com/p/6f3ee90ab7d3 示例: public static void main(String[] args) throws Interr ...

  8. 关于Java协变性的思考

    简而言之,如果A IS-A B,那么A[] IS-A B[]. 举例:现在有类型Person.Employee和Student.Employee 是一个(IS-A) Person,Student是一个 ...

  9. 关于java异常处理的思考

    学习java的过程中,初学者更多的是为了实验而写代码,而不考虑实际情况中的人机交互过程中的一些问题. 在java项目中,更多的用户不会因为你给了某些限制提醒,他就一定会按照你所给的提示来输入或者操作, ...

随机推荐

  1. 一个不错的intellj 相关的博客

    http://my.oschina.net/lujianing/blog?catalog=3300430

  2. C++常用注意事项

    new和delete:现在还没有new[][]和delete[][],所以在用这些的时候最好用循环解决,先一个指针的数组,然后再初始化,每个元素再new一下,这样就满足了多维数组的条件:比如: int ...

  3. Python发送http请求时遇到问题总结

    1.报错信息为“ERROR 'str' object has no attribute 'endwith'”,排查发现endswith方法名写错了,少了s,写成了 'endwith' if inter ...

  4. 把川普射上太阳—如何用python制作小游戏

    1.准备 开始之前,你要确保Python和pip已经成功安装在电脑上噢,如果没有,请访问这篇文章:超详细Python安装指南 进行安装. Windows环境下打开Cmd(开始—运行—CMD),苹果系统 ...

  5. Laravel 上手增删改查

    拿到一个框架,除了解框架,还要能实现基本的CURD操作. 添加 1.配置路由,指定添加页面: // routes/web.php 中增加如下: // 添加页面.存放路径 Laravel7/resour ...

  6. 详解 final 和 static

    在我们上一篇博文中提到了 fianl 这个关键字,对于这个关键字,本人在初学时也耗费了极大地心血,甚至和师兄进行了激烈的讨论,并且,在我们讨论.尝试 以及 翻阅各种资料,最终得出了合适.易懂的解释. ...

  7. [JS] 自己弄得个倒计时

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. #4018. 统计n! 尾部零

    题目出处: http://www.51cpc.com/problem/4018 题目描述 试统计正整数n的阶乘n!=1×2×3×…×n尾部连续零的个数. 输入格式 输入正整数n 输出格式 输出个数 样 ...

  9. c++使用cin、cout与c中使用scanf、printf进行输入输出的效率问题

    在c++中,我们使用cin和cout进行输入输出会比用scanf和printf更加简洁和方便,但是当程序有大量IO的时候,使用cin和cout进行输入输出会比用scanf和printf更加耗时, 在数 ...

  10. php正则验证手机、邮箱

    //验证电话private function reg_phone($phone){        if (preg_match("/^13[0-9]{1}[0-9]{8}$|15[0189] ...