Clojure Threading with Future

Clojure concurrency is easy with future. Speed improvements¬†in Clojure on modern computers come from multi-threading. Besides tapping into Java’s thread system, Clojure has it’s own easy-to-use thread system, and Clojure threads don’t get easier to use than with future.

In its simplest form, use def with a future and then then dereference the value obtained. When the future is no longer needed, make a call to shutdown-agents for the program to exit properly.

For example:

(ns clj-future.core)

(defn do-something
  "Doing something noticable."
  []
  
  "Life. Don't tell me about life.")

(defn -main
  "I don't do a whole lot."
  []
  
  ;; create a var named some-string
  ;; and make it reference our future
  (def some-string (future 
                     (do-something)))
  
  ;; dereference the future value
  ;; and print it
  (println @some-string)
  
  ;; remember to shut down agents
  ;; so the program exits normally
  (shutdown-agents))

Continue reading “Clojure Threading with Future”