Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #68: alternative to shutdown-agents #69

Merged
merged 1 commit into from
Jun 20, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions src/babashka/cli/exec.clj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
(:require
[babashka.cli :as cli :refer [merge-opts parse-opts]]
[clojure.edn :as edn]
[clojure.string :as str]))
[clojure.string :as str])
(:import [java.util.concurrent Executors ThreadFactory]))

(set! *warn-on-reflection* true)

#_:clj-kondo/ignore
(def ^:private ^:dynamic *basis* "For testing" nil)
Expand All @@ -19,6 +22,23 @@
(symbol (str ns-default) (str exec-fn))
exec-fn))

(defn- set-daemon-agent-executor
"Set Clojure's send-off agent executor (also affects futures). This is almost
an exact rewrite of the Clojure's executor, but the Threads are created as
daemons.

From https://github.com/clojure/brew-install/blob/271c2c5dd45ed87eccf7e7844b079355297d0974/src/main/clojure/clojure/run/exec.clj#L171"
[]
(let [thread-counter (atom 0)
thread-factory (reify ThreadFactory
(newThread [_ runnable]
(doto (Thread. runnable)
(.setDaemon true) ;; DIFFERENT
(.setName (format "CLI-agent-send-off-pool-%d"
(first (swap-vals! thread-counter inc)))))))
executor (Executors/newCachedThreadPool thread-factory)]
(set-agent-send-off-executor! executor)))

(defn- parse-exec-opts [args]
(let [basis (or *basis* (some->> (System/getProperty "clojure.basis")
slurp
Expand Down Expand Up @@ -62,6 +82,7 @@

(defn main [& args]
(let [[f opts] (parse-exec-opts args)]
(set-daemon-agent-executor)
(f (vary-meta opts assoc-in [:org.babashka/cli :exec] true))))

(defn -main
Expand All @@ -77,5 +98,4 @@
;;=> {:a \"1\" :b \"2\"}
```"
[& args]
(try (apply main args)
(finally (shutdown-agents))))
(apply main args))