期貨
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