CompletableFuture,Future和RxJava的Observable之间的区别 [英] Difference between CompletableFuture, Future and RxJava's Observable

查看:319
本文介绍了CompletableFuture,Future和RxJava的Observable之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道
CompletableFuture Future Observable RxJava

我所知道的都是异步但是

What I know is all are asynchronous but

Future.get()阻止线程

CompletableFuture 给出回调方法

RxJava Observable ---类似到 CompletableFuture 带有其他好处(不确定)

RxJava Observable --- similar to CompletableFuture with other benefits(not sure)

例如:如果客户需要进行多次服务调用以及何时我们使用期货(Java) Future.get()将按顺序执行...想知道它是怎么回事更好的RxJava ..

For example: if client needs to make multiple service calls and when we use Futures (Java) Future.get() will be executed sequentially...would like to know how its better in RxJava..

文档 http:// reactivex.io/intro.html

很难使用Futures来优化组合条件异步执行流程(或者不可能,因为延迟每请求在运行时有所不同)。当然,这可以完成,但它很快变得复杂(因此容易出错)或者过早地阻塞Future.get(),这消除了异步执行的好处。

真的很想知道 RxJava 如何解决这个问题。我发现从文档中很难理解。

Really interested to know how RxJava solves this problem. I found it difficult to understand from the documentation.

推荐答案

期货

期货在Java 5(2004)中引入。它们基本上是一个尚未发生的结果的占位符。它们承诺在操作完成后保留一些操作的结果。该操作可以是 Runnable 可调用的实例,提交给 ExecutorService 。操作的提交者可以使用 Future 对象来检查操作是否 get()

Futures were introduced in Java 5 (2004). They're basically placeholders for a result that hasn't happened yet. They promise to hold the result of some operation once that operation completes. The operation can be a Runnable or Callable instance that is submitted to an ExecutorService. The submitter of the operation can use the Future object to check whether the operation isDone(), or wait for it to finish using get().

示例:

/**
* A task that sleeps for a second, then returns 1
**/
public static class MyCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        Thread.sleep(1000);
        return 1;
    }

}

public static void main(String[] args) throws Exception{
    ExecutorService exec = Executors.newSingleThreadExecutor();
    Future<Integer> f = exec.submit(new MyCallable());

    System.out.println(f.isDone()); //False

    System.out.println(f.get()); //Waits until the task is done, then prints 1
}

CompletableFutures

CompletableFutures 。它们实际上是常规期货的演变,受到Google的可听期货的启发, Guava 库。它们是Futures,它还允许您将任务串联起来。你可以使用它们来告诉一些工作者线程去做一些任务X,当你完成后,用X的结果去做其他事情。这是一个简单的例子:

CompletableFutures were introduced in Java 8 (2014). They are in fact an evolution of regular Futures, inspired by Google's Listenable Futures, part of the Guava library. They are Futures that also allow you to string tasks together in a chain. You can use them to tell some worker thread to "go do some task X, and when you're done, go do this other thing using the result of X". Here's a simple example:

/**
* A supplier that sleeps for a second, and then returns one
**/
public static class MySupplier implements Supplier<Integer> {

    @Override
    public Integer get() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            //Do nothing
        }
        return 1;
    }
}

/**
* A (pure) function that adds one to a given Integer
**/
public static class PlusOne implements Function<Integer, Integer> {

    @Override
    public Integer apply(Integer x) {
        return x + 1;
    }
}

public static void main(String[] args) throws Exception {
    ExecutorService exec = Executors.newSingleThreadExecutor();
    CompletableFuture<Integer> f = CompletableFuture.supplyAsync(new MySupplier(), exec);
    System.out.println(f.isDone()); // False
    CompletableFuture<Integer> f2 = f.thenApply(new PlusOne());
    System.out.println(f2.get()); // Waits until the "calculation" is done, then prints 2
}

RxJava

RxJava 是在Netflix上创建的被动编程的整个库。一目了然,它似乎类似于 Java 8的流。除了它更强大之外。

RxJava is whole library for reactive programming created at Netflix. At a glance, it will appear to be similar to Java 8's streams. It is, except it's much more powerful.

与Futures类似,RxJava可用于将一堆同步或异步动作串联起来以创建处理管道。与一次性使用的Futures不同,RxJava适用于零个或多个项目的 streams 。包括具有无限数量项目的永无止境的流。由于拥有令人难以置信的丰富的一组运营商,它也更加灵活和强大。

Similarly to Futures, RxJava can be used to string together a bunch of synchronous or asynchronous actions to create a processing pipeline. Unlike Futures, which are single-use, RxJava works on streams of zero or more items. Including never-ending streams with an infinite number of items. It's also much more flexible and powerful thanks to an unbelievably rich set of operators.

与Java 8的流不同,RxJava还有一个背压机制,它允许它处理处理管道的不同部分在不同线程中运行的情况,以不同的速率

Unlike Java 8's streams, RxJava also has a backpressure mechanism, which allows it to handle cases in which different parts of your processing pipeline operate in different threads, at different rates.

缺点RxJava是尽管有可靠的文档,但由于涉及范式的转变,它是一个具有挑战性的库。 Rx代码也可能是调试的噩梦,特别是如果涉及多个线程,甚至更糟 - 如果需要背压。

The downside of RxJava is that despite the solid documentation, it is a challenging library to learn due to the paradigm shift involved. Rx code can also be a nightmare to debug, especially if multiple threads are involved, and even worse - if backpressure is needed.

如果你想进入它,那么官方网站上各种教程的页面以及官方文档 Javadoc 。您还可以查看一些视频,例如这一个,其中给出了简要介绍介绍Rx并介绍Rx和期货之间的差异。

If you want to get into it, there's a whole page of various tutorials on the official website, plus the official documentation and Javadoc. You can also take a look at some of the videos such as this one which gives a brief intro into Rx and also talks about the differences between Rx and Futures.

奖励:Java 9 Reactive Streams

Java 9的Reactive Streams 又名反应流库,例如 RxJava 2 Akka Streams Vertx 。它们允许这些反应库互连,同时保留所有重要的背压。

Java 9's Reactive Streams aka Flow API are a set of Interfaces implemented by various reactive streams libraries such as RxJava 2, Akka Streams, and Vertx. They allow these reactive libraries to interconnect, while preserving the all important back-pressure.

这篇关于CompletableFuture,Future和RxJava的Observable之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆