Why is the future clojure blocking the main thread?

I have a trivial lein project where the -main

future contains:

(def f (future 42))

(defn -main [& args]
  (println @f))

      

When I run lein run

it prints 42

but doesn't return.

I donโ€™t understand why heโ€™s not coming back?

How can I get it back lein run

?

+3


source to share


1 answer


Your question is really twofold:

  • Why isn't lane coming back?

lein hangs because the thread pool that supports Clojure frames is not using daemon threads, so you need to explicitly close it. 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 flow

The string (println @f)

can potentially block the main thread when "derefing" f

if the future hasn't finished its work yet.

This is a limitation of Clojure futures, which can be solved with core.async or RxClojure . I have also been working on an alternative implementation of Clojure futures that I plan to open source very soon and addresses these issues.

+6


source







All Articles