Created
November 30, 2011 06:27
-
-
Save tedpennings/1408251 to your computer and use it in GitHub Desktop.
STM demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns stm-demo | |
(:import (java.util.concurrent TimeUnit Executors ScheduledExecutorService))) | |
;; concurrency basics | |
(def scheduler (Executors/newScheduledThreadPool 3)) | |
scheduler | |
(class scheduler) | |
(defn say-hello [] | |
(println (str "Hello from " (Thread/currentThread)))) | |
(def hello-task | |
(.scheduleWithFixedDelay scheduler say-hello (long 0) (long 1) TimeUnit/SECONDS)) | |
(.cancel hello-task true) | |
;; getting into STM | |
(def account1 (ref 100)) | |
(def account2 (ref 500)) | |
(deref account1) | |
@account1 | |
@account2 | |
; uncomment the following to see what happens | |
; when attempting ref-set outside a transaction | |
;(ref-set account1 200) | |
(dosync (ref-set account1 200)) | |
@account1 | |
(defn print-balance [ref name] | |
(println (str (Thread/currentThread) " says " name " has balance of " (deref ref)))) | |
(defn print-acct1-balance [] | |
(print-balance account1 "account1")) | |
(def acct1-balance-task | |
(.scheduleWithFixedDelay scheduler print-acct1-balance (long 0) (long 1) TimeUnit/SECONDS)) | |
(defn kill-annoying-balance-task [] | |
(.cancel acct1-balance-task true) | |
(println "Killed annoying task")) | |
; kills that inquiry task after 20 seconds | |
(.schedule scheduler kill-annoying-balance-task (long 10) TimeUnit/SECONDS) | |
(dosync | |
(ref-set account1 1000000) | |
(print-balance account1 "account1") | |
(Thread/sleep 3000) | |
(print-balance account1 "account1") | |
(throw (RuntimeException. "Insufficient funds"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample output is
user=> (load-file "stm.clj")
Thread[pool-4-thread-2,5,main] says account1 has balance of 200
Thread[Thread-3,5,main] says account1 has balance of 1000000
Thread[pool-4-thread-2,5,main] says account1 has balance of 200
Thread[pool-4-thread-2,5,main] says account1 has balance of 200
Thread[pool-4-thread-2,5,main] says account1 has balance of 200
Thread[Thread-3,5,main] says account1 has balance of 1000000
java.lang.RuntimeException: Insufficient funds (stm.clj:5)
user=>
Thread[pool-4-thread-2,5,main] says account1 has balance of 200
Thread[pool-4-thread-2,5,main] says account1 has balance of 200
Thread[pool-4-thread-2,5,main] says account1 has balance of 200
Thread[pool-4-thread-2,5,main] says account1 has balance of 200
Thread[pool-4-thread-2,5,main] says account1 has balance of 200
Thread[pool-4-thread-2,5,main] says account1 has balance of 200
Killed annoying task
user=>