Java8 自定義CompletableFuture的原理解析
Java8 自定義CompletableFuture原理
Future 接口 的局限性有很多,其中一個就是需要主動的去詢問是否完成,如果等子線程的任務完成以后,通知我,那豈不是更好?
public class FutureInAction3 {
public static void main(String[] args) {
Future<String> future = invoke(() -> {
try {
Thread.sleep(10000L);
return "I am Finished.";
} catch (InterruptedException e) {
return "I am Error";
}
});
future.setCompletable(new Completable<String>() {
@Override
public void complete(String s) {
System.out.println("complete called ---- " + s);
}
@Override
public void exception(Throwable cause) {
System.out.println("error");
cause.printStackTrace();
}
});
System.out.println("....do something else .....");
System.out.println("try to get result ->" + future.get());
}
private static <T> Future<T> invoke(Callable<T> callable) {
AtomicReference<T> result = new AtomicReference<>();
AtomicBoolean finished = new AtomicBoolean(false);
Future<T> future = new Future<T>() {
private Completable<T> completable;
@Override
public T get() {
return result.get();
}
@Override
public boolean isDone() {
return finished.get();
}
// 設置完成
@Override
public void setCompletable(Completable<T> completable) {
this.completable = completable;
}
// 獲取
@Override
public Completable<T> getCompletable() {
return completable;
}
};
Thread t = new Thread(() -> {
try {
T value = callable.action();
result.set(value);
finished.set(true);
if (future.getCompletable() != null)
future.getCompletable().complete(value);
} catch (Throwable cause) {
if (future.getCompletable() != null)
future.getCompletable().exception(cause);
}
});
t.start();
return future;
}
private interface Future<T> {
T get();
boolean isDone();
// 1
void setCompletable(Completable<T> completable);
// 2
Completable<T> getCompletable();
}
private interface Callable<T> {
T action();
}
// 回調(diào)接口
private interface Completable<T> {
void complete(T t);
void exception(Throwable cause);
}
}

CompleteFuture簡單使用
Java8 中的 completeFuture 是對 Future 的擴展實現(xiàn), 主要是為了彌補 Future 沒有相應的回調(diào)機制的缺陷.
我們先看看 Java8 之前的 Future 的使用
package demos;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* @author djh on 2019/4/22 10:23
* @E-Mail 1544579459@qq.com
*/
public class Demo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService cachePool = Executors.newCachedThreadPool();
Future<String> future = cachePool.submit(() -> {
Thread.sleep(3000);
return "異步任務計算結果!";
});
// 提交完異步任務后, 主線程可以繼續(xù)干一些其他的事情.
doSomeThingElse();
// 為了獲取異步計算結果, 我們可以通過 future.get 和 輪詢機制來獲取.
String result;
// Get 方式會導致當前線程阻塞, 這顯然違背了異步計算的初衷.
// result = future.get();
// 輪詢方式雖然不會導致當前線程阻塞, 但是會導致高額的 CPU 負載.
long start = System.currentTimeMillis();
while (true) {
if (future.isDone()) {
break;
}
}
System.out.println("輪詢耗時:" + (System.currentTimeMillis() - start));
result = future.get();
System.out.println("獲取到異步計算結果啦: " + result);
cachePool.shutdown();
}
private static void doSomeThingElse() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("我的最重要的事情干完了, 我要獲取異步計算結果來執(zhí)行剩下的事情.");
}
}
輸出:
我的最重要的事情干完了, 我要獲取異步計算結果來執(zhí)行剩下的事情.
輪詢耗時:2000
獲取到異步計算結果啦: 異步任務計算結果!Process finished with exit code 0
從上面的 Demo 中我們可以看出, future 在執(zhí)行異步任務時, 對于結果的獲取顯的不那么優(yōu)雅, 很多第三方庫就針對 Future 提供了回調(diào)式的接口以用來獲取異步計算結果, 如Google的: ListenableFuture, 而 Java8 所提供的 CompleteFuture 便是官方為了彌補這方面的不足而提供的 API.
下面簡單介紹用法
package demos;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author djh on 2019/5/1 20:26
* @E-Mail 1544579459@qq.com
*/
public class CompleteFutureDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<String> completableFutureOne = new CompletableFuture<>();
ExecutorService cachePool = Executors.newCachedThreadPool();
cachePool.execute(() -> {
try {
Thread.sleep(3000);
completableFutureOne.complete("異步任務執(zhí)行結果");
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// WhenComplete 方法返回的 CompletableFuture 仍然是原來的 CompletableFuture 計算結果.
CompletableFuture<String> completableFutureTwo = completableFutureOne.whenComplete((s, throwable) -> {
System.out.println("當異步任務執(zhí)行完畢時打印異步任務的執(zhí)行結果: " + s);
});
// ThenApply 方法返回的是一個新的 completeFuture.
CompletableFuture<Integer> completableFutureThree = completableFutureTwo.thenApply(s -> {
System.out.println("當異步任務執(zhí)行結束時, 根據(jù)上一次的異步任務結果, 繼續(xù)開始一個新的異步任務!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return s.length();
});
System.out.println("阻塞方式獲取執(zhí)行結果:" + completableFutureThree.get());
cachePool.shutdown();
}
}
從上面的 Demo 中我們主要需要注意 thenApply 和 whenComplete 這兩個方法, 這兩個方法便是 CompleteFuture 中最具有意義的方法, 他們都會在 completeFuture 調(diào)用 complete 方法傳入異步計算結果時回調(diào), 從而獲取到異步任務的結果.
相比之下 future 的阻塞和輪詢方式獲取異步任務的計算結果, CompleteFuture 獲取結果的方式就顯的優(yōu)雅的多。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- Java8?CompletableFuture?runAsync學習總結submit()?execute()等
- Java?CompletableFuture實現(xiàn)多線程異步編排
- 詳解Java8?CompletableFuture的并行處理用法
- Java8 使用工廠方法supplyAsync創(chuàng)建CompletableFuture實例
- Java8 CompletableFuture 異步執(zhí)行操作
- Java并發(fā) CompletableFuture異步編程的實現(xiàn)
- Java8新的異步編程方式CompletableFuture實現(xiàn)
- Java8 CompletableFuture詳解
- Java中的CompletableFuture原理與用法
相關文章
基于javamelody監(jiān)控springboot項目過程詳解
這篇文章主要介紹了基于javamelody監(jiān)控springboot項目過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11
詳解Springboot集成sentinel實現(xiàn)接口限流入門
這篇文章主要介紹了詳解Springboot集成sentinel實現(xiàn)接口限流入門,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-11-11

