如果我将来包装一个函数并在命令行上从 leiningen 调用它,它会为运行时增加 1 整分钟。 谁能告诉我这是为什么? 您还能告诉我如何停止这种行为吗? 我想避免这额外的一分钟。
示例代码:
(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?
)))
这是因为代理使用两个线程池,第一个是固定线程池,第二个是缓存线程池。 缓存线程池终止在特定持续时间内处于非活动状态的正在运行的线程,默认值为 60 秒。这就是您看到 60 秒延迟的原因。当然,如果您手动调用关闭代理,这两个线程池都会终止,而不会留下阻止您退出的非守护进程线程。
如本问题的答案中所述,您需要在-main
方法结束时调用shutdown-agents
。
我将其作为自我回答的问答发布,因为这个问题没有提到未来,所以它没有出现在我的谷歌搜索中。果然,如果我补充:
;; soo, why does it wait for 1 minute here?
(shutdown-agents)
)))
问题消失了。