SlideShare a Scribd company logo
STM
Software Transactional Memory
in Frege - a purely functional JVM language
Parallel 2016, Heidelberg
Dierk König
Canoo
mittie
Goal: make you curious
How to program with STM

How STM works in principle

The benefits of STM

How Frege keeps you safe
Silly Clock
10010 every ms
on overflow
every so often
Transactional Variables
10010
CounterCounter
millissecs
TVar Int
Create new TVar
type Counter = TVar Int
newCounter :: STM Counter
newCounter = TVar.new 0
STM action type
Read & Write TVar
tick :: Counter -> STM ()
tick counter = do
value <- counter.read
counter.write (value + 1)
STM action (no IO)
Check transaction invariant
maxTick :: Counter -> Int -> STM ()
maxTick counter max = do
tick counter
value <- counter.read
check (value <= max)
Composition !
Consistent update
onOverflow :: Counter->Counter->Int->STM ()
onOverflow counter overflowCounter max = do
value <- counter.read
check (value == max)
tick overflowCounter
reset counter
Composition !
Type of reset enforced
reset :: Counter -> STM ()
reset counter = counter.write 0
must be STM action
Atomically
report :: Counter -> Counter -> IO ()
report millis secs = do
(millisValue, secsValue) <- atomically $ do
a <- millis.read
b <- secs.read
return (a, b)
println $ show secsValue ++ " " ++ show millisValue
Transaction demarcation

calls STM action inside IO action
Starting the threads
main _ = do
millis <- atomically newCounter
secs <- atomically newCounter
milliOverflow = 1000
runTicker = maxTick millis milliOverflow
runSec = onOverflow millis secs milliOverflow
forkOS $ forever (atomically runTicker >> Thread.sleep 1)
forkOS $ forever (atomically runSec )
forever (report millis secs >> Thread.sleep 100)
STM
Works like compare and swap but for all
TVars inside an atomically function

plus invariants (check)

plus alternatives (orElse)

plus proper exception handling

No user-managed locks -> No deadlocks
First one wins
isolated work commit
fail
retry
Problem with locks
Issue Risk
Too few locks Race conditions
Wrong lock order Deadlock
Too many locks Less throughput
Lock leakage Breaks modularity
Less concurreny errors
STM replaces all your locks just like GC
replaces manual memory management

Makes compositional and modular code

Is optimistic and thus works best in low
contention scenarios

Is not a panacea (sorry).
You must not
Use TVars outside a transaction

Do side effects inside a transaction

no REST calls,

no DB access,

no file system access, 

no I/0 at all (time, threads, random),

no object mutation,

not even a „harmless“ println!
Developer

Discipline
Pure 

Functional

Language
code inspection type system
Pure Transactions
Type inference FTW
Classic: Account transfer
deposit :: Account -> Int -> STM ()
deposit account amount = do
balance <- account.read
account.write (balance + amount)
withdraw :: Account -> Int -> STM ()
withdraw account amount =
deposit account (- amount) -- composed
limitedWithdraw :: Account -> Int -> STM ()
limitedWithdraw account amount = do
withdraw account amount -- composed
balance <- account.read
check (balance >= 0)
transfer :: Account -> Account -> Int -> STM ()
transfer from to amount = do
limitedWithdraw from amount -- composed
deposit to amount -- composed
Classic: Ant colony
Ants

Food
Pheromones
Evaporation
Reporter
Software Transactional Memory (STM) in Frege
Frege STM summary
No access to TVars outside transactions

No side effects inside transactions

TYPE SYSTEM (pure FP)

Developer discipline (everybody else)

www.frege-lang.org 

is the only option on the JVM
Dierk König
canoo
mittie
Please give feedback!
Credits
Volker Steiss
master thesis
Simon Peyton-Jones
Beautiful concurrency

More Related Content

PDF
Quick into to Software Transactional Memory in Frege
PPTX
Stm talk 2016-03-09
PPTX
More Perl Basics
PPTX
Lecture 3
PPTX
Database Recovery
PDF
Inteligencia artificial 12
PPTX
Lecture 4
PPT
Java Programming: Loops
Quick into to Software Transactional Memory in Frege
Stm talk 2016-03-09
More Perl Basics
Lecture 3
Database Recovery
Inteligencia artificial 12
Lecture 4
Java Programming: Loops

Viewers also liked (17)

PDF
FregeDay: Design and Implementation of the language (Ingo Wechsung)
PDF
Frege - consequently functional programming for the JVM
PDF
FregeFX - JavaFX with Frege, a Haskell for the JVM
PDF
Frege Tutorial at JavaOne 2015
ODP
Solr Presentation5
PDF
Os Harkins
PPT
Os Napier
PDF
Os Keysholistic
PDF
J Ruby Whirlwind Tour
PDF
FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...
PDF
FregeDay: Parallelism in Frege compared to GHC Haskell (Volker Steiss)
PDF
Os Ellistutorial
PDF
Os Keyshacks
PDF
Os Raysmith
PDF
Os Peytonjones
PDF
OCaml Labs introduction at OCaml Consortium 2012
PDF
From object oriented to functional domain modeling
FregeDay: Design and Implementation of the language (Ingo Wechsung)
Frege - consequently functional programming for the JVM
FregeFX - JavaFX with Frege, a Haskell for the JVM
Frege Tutorial at JavaOne 2015
Solr Presentation5
Os Harkins
Os Napier
Os Keysholistic
J Ruby Whirlwind Tour
FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...
FregeDay: Parallelism in Frege compared to GHC Haskell (Volker Steiss)
Os Ellistutorial
Os Keyshacks
Os Raysmith
Os Peytonjones
OCaml Labs introduction at OCaml Consortium 2012
From object oriented to functional domain modeling
Ad

Similar to Software Transactional Memory (STM) in Frege (20)

PPTX
Transactional Memory
ODP
The free lunch is over
PPT
Best-embedded-corporate-training-in-mumbai
PDF
How to make fewer errors at the stage of code writing. Part N1.
PDF
LeanXcale Presentation - Waterloo University
PDF
Defcon 22-paul-mcmillan-attacking-the-iot-using-timing-attac
PDF
Azure Streaming Analytics: A comprehensive Guide.
PPT
Lowering STM Overhead with Static Analysis
PDF
Async Debugging - A Practical Guide to survive !
PDF
The world computer
PPT
.Net Enterprise Services and their Implementations
PDF
030 cpp streams
PDF
Monitoring your Python with Prometheus (Python Ireland April 2015)
KEY
Rate Limiting at Scale, from SANS AppSec Las Vegas 2012
PPT
Coding style for good synthesis
PPT
TinyOS 2.1 tutorial at IPSN 2009
PDF
How to deploy & optimize eZ Publish
PPTX
Column store indexes and batch processing mode (nx power lite)
PDF
Building a blockchain on tendermint
PPTX
MongoDB.local Sydney: How and When to Use Multi-Document Distributed Transact...
Transactional Memory
The free lunch is over
Best-embedded-corporate-training-in-mumbai
How to make fewer errors at the stage of code writing. Part N1.
LeanXcale Presentation - Waterloo University
Defcon 22-paul-mcmillan-attacking-the-iot-using-timing-attac
Azure Streaming Analytics: A comprehensive Guide.
Lowering STM Overhead with Static Analysis
Async Debugging - A Practical Guide to survive !
The world computer
.Net Enterprise Services and their Implementations
030 cpp streams
Monitoring your Python with Prometheus (Python Ireland April 2015)
Rate Limiting at Scale, from SANS AppSec Las Vegas 2012
Coding style for good synthesis
TinyOS 2.1 tutorial at IPSN 2009
How to deploy & optimize eZ Publish
Column store indexes and batch processing mode (nx power lite)
Building a blockchain on tendermint
MongoDB.local Sydney: How and When to Use Multi-Document Distributed Transact...
Ad

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPT
Teaching material agriculture food technology
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
cuic standard and advanced reporting.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
KodekX | Application Modernization Development
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Modernizing your data center with Dell and AMD
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Encapsulation_ Review paper, used for researhc scholars
Encapsulation theory and applications.pdf
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Unlocking AI with Model Context Protocol (MCP)
Reach Out and Touch Someone: Haptics and Empathic Computing
“AI and Expert System Decision Support & Business Intelligence Systems”
Teaching material agriculture food technology
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Chapter 3 Spatial Domain Image Processing.pdf
Spectral efficient network and resource selection model in 5G networks
cuic standard and advanced reporting.pdf
MYSQL Presentation for SQL database connectivity
KodekX | Application Modernization Development
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Modernizing your data center with Dell and AMD
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Mobile App Security Testing_ A Comprehensive Guide.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Encapsulation_ Review paper, used for researhc scholars

Software Transactional Memory (STM) in Frege

  • 1. STM Software Transactional Memory in Frege - a purely functional JVM language Parallel 2016, Heidelberg
  • 3. Goal: make you curious How to program with STM How STM works in principle The benefits of STM How Frege keeps you safe
  • 4. Silly Clock 10010 every ms on overflow every so often
  • 6. Create new TVar type Counter = TVar Int newCounter :: STM Counter newCounter = TVar.new 0 STM action type
  • 7. Read & Write TVar tick :: Counter -> STM () tick counter = do value <- counter.read counter.write (value + 1) STM action (no IO)
  • 8. Check transaction invariant maxTick :: Counter -> Int -> STM () maxTick counter max = do tick counter value <- counter.read check (value <= max) Composition !
  • 9. Consistent update onOverflow :: Counter->Counter->Int->STM () onOverflow counter overflowCounter max = do value <- counter.read check (value == max) tick overflowCounter reset counter Composition !
  • 10. Type of reset enforced reset :: Counter -> STM () reset counter = counter.write 0 must be STM action
  • 11. Atomically report :: Counter -> Counter -> IO () report millis secs = do (millisValue, secsValue) <- atomically $ do a <- millis.read b <- secs.read return (a, b) println $ show secsValue ++ " " ++ show millisValue Transaction demarcation
 calls STM action inside IO action
  • 12. Starting the threads main _ = do millis <- atomically newCounter secs <- atomically newCounter milliOverflow = 1000 runTicker = maxTick millis milliOverflow runSec = onOverflow millis secs milliOverflow forkOS $ forever (atomically runTicker >> Thread.sleep 1) forkOS $ forever (atomically runSec ) forever (report millis secs >> Thread.sleep 100)
  • 13. STM Works like compare and swap but for all TVars inside an atomically function
 plus invariants (check)
 plus alternatives (orElse)
 plus proper exception handling No user-managed locks -> No deadlocks
  • 14. First one wins isolated work commit fail retry
  • 15. Problem with locks Issue Risk Too few locks Race conditions Wrong lock order Deadlock Too many locks Less throughput Lock leakage Breaks modularity
  • 16. Less concurreny errors STM replaces all your locks just like GC replaces manual memory management Makes compositional and modular code Is optimistic and thus works best in low contention scenarios Is not a panacea (sorry).
  • 17. You must not Use TVars outside a transaction Do side effects inside a transaction
 no REST calls,
 no DB access,
 no file system access, 
 no I/0 at all (time, threads, random),
 no object mutation,
 not even a „harmless“ println!
  • 21. Classic: Account transfer deposit :: Account -> Int -> STM () deposit account amount = do balance <- account.read account.write (balance + amount) withdraw :: Account -> Int -> STM () withdraw account amount = deposit account (- amount) -- composed limitedWithdraw :: Account -> Int -> STM () limitedWithdraw account amount = do withdraw account amount -- composed balance <- account.read check (balance >= 0) transfer :: Account -> Account -> Int -> STM () transfer from to amount = do limitedWithdraw from amount -- composed deposit to amount -- composed
  • 24. Frege STM summary No access to TVars outside transactions
 No side effects inside transactions TYPE SYSTEM (pure FP)
 Developer discipline (everybody else) www.frege-lang.org 
 is the only option on the JVM
  • 25. Dierk König canoo mittie Please give feedback! Credits Volker Steiss master thesis Simon Peyton-Jones Beautiful concurrency