Roger Allen
Roger Allen

Reputation: 2312

leiningen run does not return for one minute after invoking future

If I wrap a function in a future and invoke this from leiningen on the commandline, it adds 1 full minute to the runtime. Can any one tell me why this is? Can you also tell me how to stop this behavior? I'd like to avoid this extra minute.

Example code:

(ns futest.core
  (:gen-class))

(defn testme []
  (Thread/sleep 2000)
  42)

(defn -main
  [& args]
  (if (= (nth args 0) "a")
    ;; either run a simple function that takes 2 seconds
    (do
      (println "no future sleep")
      (let [t (testme)]
        (println t))
      (println "done."))
    ;; or run a simple function that takes 2 seconds as a future
    (do
      (println "future sleep")
      (let [t (future (testme))]
        (println @t))
      (println "done.")
      ;; soo, why does it wait for 1 minute here?
      )))

Upvotes: 4

Views: 163

Answers (2)

Shlomi
Shlomi

Reputation: 4748

this is because agents uses two threadpools, the first is a fixed threadpool and the second a cached threadpool. cached threadpool terminates running threads that were inactive for a certain duration, the default being 60 seconds. This is the reason you see the 60 seconds delay. Of course, if you manually call shutdown-agents both these threadpools terminate leaving no non-daemon threads that blocks your exit.

Upvotes: 3

Roger Allen
Roger Allen

Reputation: 2312

As noted in the answer to this question you need to call shutdown-agents at the end of your -main method.

I'm posting this as self-answered Q&A since that question doesn't mention future, so it didn't turn up on my google searches. Sure enough, if I add:

  ;; soo, why does it wait for 1 minute here?
  (shutdown-agents)
  )))

the problem goes away.

Upvotes: 2

Related Questions