introduction to clojure's stm

15
Clojure’s Software Transactional Memory @fronx at @cljugb 12/2011 Thursday, December 15, 11

Upload: fronx-wurmus

Post on 29-Aug-2014

1.831 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Introduction to Clojure's STM

Clojure’s

SoftwareTransactionalMemory

@fronx at @cljugb 12/2011

Thursday, December 15, 11

Page 2: Introduction to Clojure's STM

what’s it good for?

Thursday, December 15, 11

Page 3: Introduction to Clojure's STM

it’s pretty much useless

unless you have:

concurrency

shared state

changes to state

Thursday, December 15, 11

Page 4: Introduction to Clojure's STM

the pitch

“It allows you to docoordinated changewithout the complexityof locking.”

— Rich Hickeyhttp://www.infoq.com/interviews/hickey-clojure

Thursday, December 15, 11

Page 5: Introduction to Clojure's STM

kind of likedatabase transactions.

but in memory.

Thursday, December 15, 11

Page 6: Introduction to Clojure's STM

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

Page 7: Introduction to Clojure's STM

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

Page 8: Introduction to Clojure's STM

broken example(using atoms)

Thursday, December 15, 11

Page 9: Introduction to Clojure's STM

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

Page 10: Introduction to Clojure's STM

sharing state

coordinated independent

synchronous

asynchronous

ref atom

– agent

mutate inSTM only!

receive messageand return

Thursday, December 15, 11

Page 11: Introduction to Clojure's STM

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

Page 12: Introduction to Clojure's STM

working and slightly different example

(using STM)

Thursday, December 15, 11

Page 13: Introduction to Clojure's STM

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

Page 14: Introduction to Clojure's STM

what to think about

is it okay if others make changes in parallel?

commute

multi-ref constraints?

ensure

Thursday, December 15, 11

Page 15: Introduction to Clojure's STM

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