Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Integralist/741c2577e97fd8e466a4 to your computer and use it in GitHub Desktop.
Save Integralist/741c2577e97fd8e466a4 to your computer and use it in GitHub Desktop.
Clojure Thread State
(def current-account (ref 500))
(def savings-account (ref 600))
(println (str "current-account:" current-account))
(println (str "savings-account:" savings-account))
(defn withdraw [from constraint amount]
(dosync
(let [total (+ @from (ensure constraint))]
(Thread/sleep 1000)
(println (str (Thread/currentThread) " - " (.isInterrupted (Thread/currentThread)) "\n"))
(println (str (Thread/currentThread) " - " (.getState (Thread/currentThread)) "\n"))
(println (str (Thread/currentThread) " - " (.getPriority (Thread/currentThread)) "\n"))
(if (>= (- total amount) 1000)
(alter from - amount)
(println "Sorry, can't withdraw due to constraint violation\n")))))
(println "STATE BEFORE MODIFYING")
(println "Current Account balance is" @current-account)
(println "Savings Account balance is" @savings-account)
(println "Total balance is" (+ @current-account @savings-account))
(future (withdraw current-account savings-account 100))
(future (withdraw savings-account current-account 100))
(Thread/sleep 4000)
(println "STATE AFTER MODIFYING")
(println "Current Account balance is" @current-account)
(println "Savings Account balance is" @savings-account)
(println "Total balance is" (+ @current-account @savings-account))
@Integralist
Copy link
Author

The function (Thread/currentThread) outputs Thread[clojure-agent-send-off-pool-15,5,main].

I expected currentThread (at that point in the application) to refer to the new thread spawned by (future ...)

Reading the docs for (future ...) (https://clojuredocs.org/clojure.core/future) suggests when executed it will...

"invoke the body in another thread"

...so why (Thread/currentThread) is saying the "main" thread is the one current one, I'm not sure?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment