Does the future always create a new stream?

Let's say I do this:

(future
  (do-the-thing))

I'm sure no matter what it does (do-the-thing),

  • Will a completely new thread be created, instead of getting it from the pool or something like that?
  • nothing else (do-the-thing)will ever work in this new thread?
  • Once (do-the-thing)executed in this new thread, does the thread terminate?

If not, under what circumstances will these assumptions be false?

+4
source share
1 answer

Short answer No

From clojure core.clj :

(defmacro future
...
  [& body] `(future-call (^{:once true} fn* [] ~@body)))
...

(defn future-call 
...
  [f]
  (let [f (binding-conveyor-fn f)
        fut (.submit clojure.lang.Agent/soloExecutor ^Callable f)]
...

So, the performer of the future is clojure.lang.Agent/soloExecutor.

Agent.java:

volatile public static ExecutorService soloExecutor = Executors.newCachedThreadPool(
    createThreadFactory("clojure-agent-send-off-pool-%d", sendOffThreadPoolCounter));

, soloExecutor Executors.newCachedThreadPool()

Executors.newCachedThreadPool:

, , , . , . , . , . , , . , , , - . , , (, -) ThreadPoolExecutor.

, - (do-the-thing), , 60 , .

Executors.newCachedThreadPool :

(doseq [i (for [x (range 10)] (future (Thread/sleep 1000) (.getId (Thread/currentThread))))] (print @i) (print " "))

clojure, :

50 49 48 47 46 45 44 43 42 41 nil

. 5 , :

50 49 43 41 45 42 46 47 48 44 nil

, .

60 , :

60 59 58 57 56 55 54 53 52 51 nil

, , , .

+4

All Articles