Why does a clojure future block the main thread?

北战南征 提交于 2020-01-24 10:56:49

问题


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:

  1. 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))
  1. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!