introduction to clojure's stm
DESCRIPTION
TRANSCRIPT
Clojure’s
SoftwareTransactionalMemory
@fronx at @cljugb 12/2011
Thursday, December 15, 11
what’s it good for?
Thursday, December 15, 11
it’s pretty much useless
unless you have:
concurrency
shared state
changes to state
Thursday, December 15, 11
the pitch
“It allows you to docoordinated changewithout the complexityof locking.”
— Rich Hickeyhttp://www.infoq.com/interviews/hickey-clojure
Thursday, December 15, 11
kind of likedatabase transactions.
but in memory.
Thursday, December 15, 11
example
ab c d
e
1 9 5 7 3 10 42 6 8
4
threads
shared state
changing state
4
solution: do it atomically!
Thursday, December 15, 11
atomsuser=> (def my-atom (atom 0))
#'user/my-atom
user=> @my-atom
0
user=> (swap! my-atom inc)
1
user=> @my-atom
1
user=> (swap! my-atom (fn [n] (* (+ n n) 2)))
4
(No STM here.)
Thursday, December 15, 11
broken example(using atoms)
Thursday, December 15, 11
changing state
atomic (acts as one point in time)
consistent (from valid state to valid state)
isolated (changes are local until committed)
Thursday, December 15, 11
sharing state
coordinated independent
synchronous
asynchronous
ref atom
– agent
mutate inSTM only!
receive messageand return
Thursday, December 15, 11
STM functions
ref
dosync
set-ref
alter
commute
ensure
io!
reference to a collection
transaction
set new value
set new value via a function
set new value and don’t block
block writes by others
IllegalStateException
Thursday, December 15, 11
working and slightly different example
(using STM)
Thursday, December 15, 11
STM functions
ref
dosync
set-ref
alter
commute
ensure
io!
reference to a collection
transaction
set new value
set new value via a function
set new value and don’t block
block writes by others
IllegalStateException
Thursday, December 15, 11
what to think about
is it okay if others make changes in parallel?
commute
multi-ref constraints?
ensure
Thursday, December 15, 11
how does it work?
MVCC, snapshot isolation
persistent data structures
on-commit evaluation
http://java.ociweb.com/mark/stm/article.html
Thursday, December 15, 11