wolfer
wolfer

Reputation: 7

clojure, freeze after call future and same

I have test script

(defn foo [] ( print "OK!" ))
(print "main")
(future-call foo)
(print "end")

When I run it in REPL, always fine

user=> (defn foo [] ( print "OK!" ))
#'user/foo
user=> (print "main")
mainnil
user=> (future-call foo)
OK!#<core$future_call$reify__6320@1d4997: nil>
user=> (print "end")
endnil

But when I run it from console, I have strange freeze after the code has finished executing

$ time clojure-1.6 /tmp/1.clj 
mainend
real    1m1.672s
user    0m2.229s
sys     0m0.143s

mainend displayed almost immediately, but returns to the shell takes about a minute.

pmap also work strange

(defn foo [x] ( print x ))
(print "main")
(pmap foo [1 2 3 4 5 6 7 8 9 0])
(print "end")

will displayed

$ time clojure-1.6 /tmp/1.clj 
main12365409end
real    1m1.688s
user    0m2.320s
sys     0m0.114s

I known that ..365.. it's normal for concurrency code, but why 7 and 8 not displayed?

Upvotes: 0

Views: 366

Answers (1)

Daniel Compton
Daniel Compton

Reputation: 14569

You need to call shutdown-agents

Note: If you leave out the call to (shutdown-agents), the program will on most (all?) OS/JVM combinations "hang" for 1 minute before the process exits. It is waiting for a thread created by the future call to be shut down. shutdown-agents will shut them down immediately, or (System/exit ) will exit immediately without waiting for them to shut down.

This wait occurs even if you use futures indirectly through some other Clojure functions that use them internally, such as pmap or clojure.java.shell/sh

From https://clojuredocs.org/clojure.core/future

Upvotes: 1

Related Questions