CompletableFuture 完成时修改 HashMap

Modify HashMap when CompletableFuture is finished

我有一个多模块系统,其中一个模块处理我的数据库存储。这是保存文件的方法:

    public CompletableFuture<?> runTransaction() {
        return CompletableFuture.runAsync(() -> {
            TransactionBody txnBody = (TransactionBody<String>) () -> {
                MongoCollection<Document> collection = transaction.getDatabase().getCollection(transaction.getCollection().toString());
                collection.insertOne(session, Document.parse(json));
                return "Completed";
            };
            try {
                session.withTransaction(txnBody);
            } catch (MongoException ex) {
                throw new UncheckedMongoException(ex);
            }
        });
    }

json 实例在对象构造函数中向下传递。然而,由于这将被多个模块使用,每个单独的缓存系统,我试图弄清楚调用者如何修改数据结构,如果这个方法完成没有任何错误。

例如

public void createClan(Transaction transaction, int id, int maxPlayers) {
                MongoTransaction mongoTransaction = (MongoTransaction) transaction;
                Clan clan = new Clan(id, maxPlayers);
                String json = gson.toJson(clan);

                TransactionExecutor executor = new MongoTransactionExecutor(mongoTransaction, json);
                executor.runTransaction(); //Returns the completableFuture instance generated by the method. Modify hashmap here.
        }

我已经尝试阅读文档,但是有点混乱,感谢您的帮助!

如评论所述,可以考虑两种方案。

第一个选项是使用 CompletableFuture#get 将异步性质转换为同步性质。这样,代码执行是在阻塞上下文中。

public void createClan(Transaction transaction, int id, int maxPlayers) {
   MongoTransaction mongoTransaction = (MongoTransaction) transaction;
   Clan clan = new Clan(id, maxPlayers);   
   String json = gson.toJson(clan);
   TransactionExecutor executor = new MongoTransactionExecutor(mongoTransaction, json);
   try {
      Object obj = executor.runTransaction().get();
      // HashMap update here
   } catch(Exception e) {
      //handle exceptions
   }
}

第二个选项是保持异步性质,并使用 thenRun 链接(有许多 then 选项可用)。这种方式更像是一种非阻塞上下文。

 public void createClan(Transaction transaction, int id, int maxPlayers) {
   MongoTransaction mongoTransaction = (MongoTransaction) transaction;
   final Clan clan = new Clan(id, maxPlayers);   
   String json = gson.toJson(clan);
   TransactionExecutor executor = new MongoTransactionExecutor(mongoTransaction, json);
   try {
      executor.runTransaction().thenRun(() -> updateHashMap(clan));
   } catch(Exception e) {
      //handle exceptions
   }
}