Skip to content

Commit 792467b

Browse files
authored
Fix: the shutdown hook should be removed when the process ends to avoid a memory leak. (#173)
* Fix: the shutdown hook should be removed when the process ends to avoid a memory leak. * Running the `:shutdown` hook as soon as the child process ends.
1 parent b13607a commit 792467b

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

src/babashka/process.cljc

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -413,8 +413,20 @@
413413
prev
414414
cmd)]
415415
(when shutdown
416-
(-> (Runtime/getRuntime)
417-
(.addShutdownHook (Thread. (fn [] (shutdown res))))))
416+
(let [hook (Thread. (fn [] (shutdown res)))]
417+
(-> (Runtime/getRuntime)
418+
(.addShutdownHook hook))
419+
(if-before-jdk8
420+
nil ;; throwing an exception here would commit breakage, therefore accept the memory leak for jdk8
421+
(-> (.onExit proc)
422+
(.thenRun (fn []
423+
;; To avoid a memory leak remove the hook when the process ends:
424+
(-> (Runtime/getRuntime)
425+
(.removeShutdownHook hook))
426+
;; But run the shutdown hook to ensure that cleanup
427+
;; tasks are executed:
428+
(.start hook)
429+
))))))
418430
(when exit-fn
419431
(if-before-jdk8
420432
(throw (ex-info "The `:exit-fn` option is not support on JDK 8 and lower." res))
@@ -471,7 +483,8 @@
471483
- `:cmd` - a vector of the tokens of the command to be executed (e.g. `[\"ls\" \"foo\"]`)
472484
- `:shutdown`: shutdown hook, defaults to `nil`. Takes process
473485
map. Typically used with `destroy` or `destroy-tree` to ensure long
474-
running processes are cleaned up on shutdown.
486+
running processes are cleaned up on shutdown. The shutdown hook is
487+
executed as soon as the child process ends.
475488
- `:exit-fn`: a function which is executed upon exit. Receives process map as argument. Only supported in JDK11+."
476489
{:arglists '([opts? & args])}
477490
[& args]

0 commit comments

Comments
 (0)