期货
Futures在Java 5中(2004年)进行了介绍。它们是承诺在操作完成后保留操作结果的对象。例如,当任务(即Runnable或Callable)被提交给执行者时。呼叫者可以使用未来对象来检查操作isDone(),或等待它完成使用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用Java 8(2014)进行了介绍。它们实际上是由谷歌的Listenable Futures(Guava库的一部分)启发的定期期货的演变。他们是期货,也允许你在一个链中串起任务。你可以用它们来告诉一些工作者线程“去做一些任务X,等你完成后,用X的结果去做这件事情”。这里有一个简单的例子:
/**
* 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公司创造了reactive programming整个图书馆。一目了然,它看起来与Java 8's streams类似。它是,除了它更强大。
与期货类似,RxJava可用于将一堆同步或异步操作串起来以产生一个或多个有意义的结果。然而,不像期货一次性使用,RxJava的数据流可以处理零个或多个项目,包括具有无限数量项目的永无止境的流。它的灵活性和流畅性也得益于令人难以置信的丰富set of operators。
与Java 8的流不同,RxJava有一个backpressure机制,它允许它处理不同部分处理流在不同线程中以不同速率运行的情况。
RxJava的不足之处在于,尽管文档相当好,但由于涉及到范式转换,它是一个具有挑战性的图书馆。 Rx代码也可能成为调试的噩梦,特别是涉及多个线程时,甚至更糟 - 如果需要回压。如果你想进入它,官方网站上有各种教程的整个page,加上官方的documentation和Javadoc。您还可以查看一些视频,例如this one,其中介绍了Rx的简要介绍,并讨论了Rx和期货之间的区别。
加成:爪哇9个反应流
Java 9's Reactive Streams又名Flow API是一组由各种reactive streams库如RxJava 2,Akka Streams,和Vertx实现的接口。它们允许这些反应性库互连,同时保留所有重要的背压。
您是否阅读过每个文档的文档?我对RxJava完全不熟悉,但文档一目了然。这与两个期货似乎并不具有可比性。 – Vulcan
我已经经历了,但无法得到它与Java未来有多大的不同......纠正我,如果我错了 – shiv455
如何观察类似于期货? – Vulcan