我正在与返回 CompletableFuture
的 Java API 交互。
现在,如果我有这些 [cf1 cf2 cf3 …]
的数组,我如何给它们 all 一秒钟的时间来完成,并在一秒钟后收集它们产生的所有内容?
类似于:
(def vec-of-cf [cf1 cf2 cf3])
(get-all vec-of-cf 1000 ::timeout)
;; no more than 1 second later, I should have my vector of realized CompletableFuture, possibly holding a `::timeout` value if they did not have time to finish
我认为这类似于 Scala flatmap
(?)。
最佳答案
您可能会使用 CompletableFuture.allOf
为了获得一个可完成的 future ,您可以阻塞等待所有任务完成或超时所需的时间(因此等待时间可能比超时时间短 - 所有任务最多一秒,不一定在一秒后)然后迭代如果完成,则在原始 future 上获得它们的值(value):
(def vec-of-cf [cf1 cf2 cf3])
(let [all-of (CompletableFuture/allOf (into-array vec-of-cf))]
(try
(.get all-of timeout)
(catch java.util.concurrent.TimeoutException e))
(->> vec-of-cf
(filter #(.isDone %))
(map #(.get %))))
关于java - Clojure实现带超时的 future vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47379054/