问题
I have a trivial lein project where -main
contains a future:
(def f (future 42))
(defn -main [& args]
(println @f))
When I run lein run
it prints 42
but does not return.
I don't understand why it does not return ?
How do I get lein run
to return ?
回答1:
Your question is really twofold:
- Why does lein not return?
lein hangs because the thread pool which backs Clojure futures does not use daemon threads so you have to explicitly shut it down. If you change your code to the following, it should work:
(def f (future 42))
(defn -main [& args]
(println @f)
(shutdown-agents))
- Futures block the main thread
The line (println @f)
can potentially block the main thread when "derefing" f
if the future hasn't finished its job yet.
This is a limitation of Clojure futures that can be addressed using core.async or RxClojure. I've also been working on an alternative implementation of futures for Clojure that I plan to open source very soon and addresses these issues.
来源:https://stackoverflow.com/questions/27014241/why-does-a-clojure-future-block-the-main-thread