Future vs Thread: Which is better for working with channels in core.async?

Viewed 4762

When working with channels, is future recommended or is thread? Are there times when future makes more sense?

Rich Hickey's blog post on core.async recommends using thread rather than future:

While you can use these operations on threads created with e.g. future, there is also a macro, thread , analogous to go, that will launch a first-class thread and similarly return a channel, and should be preferred over future for channel work.

~ http://clojure.com/blog/2013/06/28/clojure-core-async-channels.html

However, a core.async example makes extensive use of future when working with channels:

(defn fake-search [kind]
  (fn [c query]
    (future
     (<!! (timeout (rand-int 100)))
     (>!! c [kind query]))))

~ https://github.com/clojure/core.async/blob/master/examples/ex-async.clj

3 Answers

Aside from which threadpool things are run in (as pointed out in another answer), the main difference between async/thread and future is this:

  • thread will return a channel which only lets you take! from the channel once before you just get nil, so good if you need channel semantics, but not ideal if you want to use that result over and over
  • in contrast, future returns a dereffable object, which once the thread is complete will return the answer every time you deref , making it convenient when you want to get this result more than once, but this comes at the cost of channel semantics

If you want to preserve channel semantics, you can use async/thread and place the result on (and return a) async/promise-chan, which, once there's a value, will always return that value on later take!s. It's slightly more work than just calling future, since you have to explicitly place the result on the promise-chan and return it instead of the thread channel, but buys you interoperability with the rest of the core.async infrastructure.

It almost makes one wonder if there shouldn't be a core.async/thread-promise and core.async/go-promise to make this more convenient...

Related