Skip to content

开发和应用场景

主要用來紀錄下開發中解決過的問題,圍繞

  1. 應用場景
  2. 實現

CompletableFuture 特性

應用場景

質押合約中有 X 個質押池子,如果需要查詢用戶 Y 在每一個池子中的餘額,需要發起 X 次 RPC 請求,同步調用顯然不現實,可以通過 CompletableFuture 特性去完成餘額查詢

實現

java
List<CompletableFuture<String>> allFutures = Stream.of(
    CompletableFuture.supplyAsync(() -> web3Service.checkUserBalance(user, 0)),
    CompletableFuture.supplyAsync(() -> web3Service.checkUserBalance(user, 1)),
    CompletableFuture.supplyAsync(() -> web3Service.checkUserBalance(user, 2)),
    CompletableFuture.supplyAsync(() -> web3Service.checkUserBalance(user, 3)),
    ...
).toList();

CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(allFutures.toArray(new CompletableFuture[0]));
allDoneFuture.join();

List<String> results = allFutures.stream()
        .map(CompletableFuture::join)
        .toList();

Powered by VitePress © 2024 Edison. All rights reserved.