SlideShare a Scribd company logo
1 of 17
SOFTWARE TRANSACTIONAL MEMORY
@DUSTINWHITNEY
Alternative to lock-based synchronization
Analogous to database transactions
ACI (ACID with out the „D‟)
Simple! (well… simplier)
WHAT IS STM?
libraryDependencies += ("org.scala-stm" %% "scala-stm" % "0.7")
import scala.concurrent.stm._
val protectedInt = Ref(0)
atomic{ implicit transaction=>
val currentValue = protectedInt.get
protectedInt.set(currentValue + 1)
}
WHAT DOES IT LOOK LIKE?
ATOMIC
val protectedInt = Ref(0)
val anotherProtectedInt = Ref(0)
atomic{ implicit transaction =>
val currentValue = protectedInt.get
protectedInt.set(currentValue + 1)
val anotherCurrentValue = anotherProtectedInt.get
anotherProtectedInt.set(anotherCurrentValue + 1)
}
CONSISTENT
val protectedInt = Ref(0)
atomic{ transaction =>
val currentValue = protectedInt.get(transaction)
protectedInt.set(currentValue + 1)(transaction)
}
val protectedInt = Ref(0)
atomic{ implicit transaction =>
val currentValue = protectedInt.get
protectedInt.set(currentValue + 1)
}
ISOLATED
STM is not Durable
DURABLE
ADVANTAGES: DEADLOCK / LIVELOCK
val protectedInt = Ref(0)
atomic{ implicit transaction =>
val currentValue = protectedInt.get
protectedInt.set(currentValue + 1)
}
ADVANTAGES: PRIORITY INVERSION
val protectedInt = Ref(0)
atomic{ implicit transaction =>
val currentValue = protectedInt.get
protectedInt.set(currentValue + 1)
}
ADVANTAGES: COMPOSABILITY
val protectedInt = Ref(0)
val anotherProtedtedInt = Ref(0)
atomic{ implicit transaction =>
val currentValue = protectedInt.get
protectedInt.set(currentValue + 1)
atomic{ implicit transaction =>
val anotherCurrentValue = anotherProtectedInt.get
val anotherProctedInt.set(anotherCurrentValue + 1)
}
}
GOTCHAS: IMMUTABILITY!
// bad!
val badMap= Ref(new java.util.HashMap[String, Int]())
val mutableMap = atomic{ implicit transaction => badMap.get }
mutableMap.put(“Wrong!”, 666)
// good
val goodMap = Ref(Map(“Good” -> 7))
atomic{ implicit transaction =>
val tempMap = goodMap.get
goodMap.set(tempMap + (“Good” -> 777))
}
GOTCHAS: REFERENTIAL TRANSPARENCY
//bad
val protectedString = Ref("This is a string")
val time = System.currentTimeMillis
atomic{ implicit transaction =>
if(time % 2 == 0) protectedString.set("Time was even")
else protectedString.set("Time was odd")
}
//good
atomic{ implicit transaction =>
val time = System.currentTimeMillis
if(time % 2 == 0) protectedString.set("Time was even")
else protectedString.set("Time was odd")
}
EXTENDED EXAMPLE: STM
case class Account(number: Int, balance: Int)
val accounts = Ref(Map(
1 -> Account(1, 100),
2 -> Account(2, 100)
))
def transfer(to: Int, from: Int, amount: Int){
atomic{ implicit transaction =>
val map = accounts.get
val toAccount = map(to)
val fromAccount = map(from)
accounts.set(
map
+ (to -> (toAccount.copy(balance = toAccount.balance + amount)))
+ (from -> (fromAccount.copy(balance = fromAccount.balance - amount)))
)
}
}
EXTENDED EXAMPLE: SYNCHRONIZED
import java.util._
private val accounts = new HashMap[Int, Account]()
accounts.put(1, Account(1, 100))
accounts.put(2, Account(2, 100))
def transfer(to: Int, from: Int, amount: Int){
accounts.synchronized{
val toAccount = accounts.get(to)
val fromAccount = accounts.get(from)
accounts.put(to, (toAccount.copy(balance = toAccount.balance + amount)))
accounts.put(from, (fromAccount.copy(balance = fromAccount.balance - amount)))
}
}
EXTENDED EXAMPLE: SYNCHRONIZED2
import java.util.concurrent._
private val accounts = ConcurrentHashMap[Int, Account]()
accounts.put(1, Account(1, 100))
accounts.put(2, Account(2, 100))
def transfer(to: Int, from: Int, amount: Int){
val toAccount = accounts.get(to)
val fromAccount = accounts.get(from)
toAccount.synchronized{
fromAccount.synchronized{
accounts.put(to, (toAccount.copy(balance = toAccount.balance + amount)))
accounts.put(from, (fromAccount.copy(balance = fromAccount.balance - amount)))
}
}
}
EXTENDED EXAMPLE: SYNCHRONIZED3
import java.util.concurrent._
private val accounts = ConcurrentHashMap[Int, Account]()
accounts.put(1, Account(1, 100))
accounts.put(2, Account(2, 100))
def transfer(to: Int, from: Int, amount: Int){
val toAccount = accounts.get(to)
val fromAccount = accounts.get(from)
val (firstLock, secondLock) = if(to > from) (toAccount, fromAccount)
else (fromAccount, toAccount)
firstLock.synchronized{
secondLock.synchronized{
accounts.put(to, (toAccount.copy(balance = toAccount.balance + amount)))
accounts.put(from, (fromAccount.copy(balance = fromAccount.balance - amount)))
}
}
}
Questions?

More Related Content

What's hot

Ejercicios
EjerciciosEjercicios
Ejercicios
leonharo
 

What's hot (20)

Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223
 
Ejercicios
EjerciciosEjercicios
Ejercicios
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
 
CR17 - Designing a database like an archaeologist
CR17 - Designing a database like an archaeologistCR17 - Designing a database like an archaeologist
CR17 - Designing a database like an archaeologist
 
Designing a database like an archaeologist
Designing a database like an archaeologistDesigning a database like an archaeologist
Designing a database like an archaeologist
 
Programação assíncrona utilizando Coroutines
Programação assíncrona utilizando CoroutinesProgramação assíncrona utilizando Coroutines
Programação assíncrona utilizando Coroutines
 
Pivorak Clojure by Dmytro Bignyak
Pivorak Clojure by Dmytro BignyakPivorak Clojure by Dmytro Bignyak
Pivorak Clojure by Dmytro Bignyak
 
“SOLID principles in PHP – how to apply them in PHP and why should we care“ b...
“SOLID principles in PHP – how to apply them in PHP and why should we care“ b...“SOLID principles in PHP – how to apply them in PHP and why should we care“ b...
“SOLID principles in PHP – how to apply them in PHP and why should we care“ b...
 
Using spark data frame for sql
Using spark data frame for sqlUsing spark data frame for sql
Using spark data frame for sql
 
SOLID principles in practice: the Clean Architecture
SOLID principles in practice: the Clean ArchitectureSOLID principles in practice: the Clean Architecture
SOLID principles in practice: the Clean Architecture
 
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando CoroutinesTDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
TDC2018SP | Trilha Kotlin - Programacao assincrona utilizando Coroutines
 
Javascript Arrays
Javascript ArraysJavascript Arrays
Javascript Arrays
 
The Ring programming language version 1.8 book - Part 73 of 202
The Ring programming language version 1.8 book - Part 73 of 202The Ring programming language version 1.8 book - Part 73 of 202
The Ring programming language version 1.8 book - Part 73 of 202
 
Swift study: Closure
Swift study: ClosureSwift study: Closure
Swift study: Closure
 
The Ring programming language version 1.4 book - Part 6 of 30
The Ring programming language version 1.4 book - Part 6 of 30The Ring programming language version 1.4 book - Part 6 of 30
The Ring programming language version 1.4 book - Part 6 of 30
 
Java Se next Generetion
Java Se next GeneretionJava Se next Generetion
Java Se next Generetion
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲーム
 
PROGRAM pod
PROGRAM podPROGRAM pod
PROGRAM pod
 
Monadologie
MonadologieMonadologie
Monadologie
 

Similar to Pellucid stm

.Net Enterprise Services and their Implementations
.Net Enterprise Services and their Implementations.Net Enterprise Services and their Implementations
.Net Enterprise Services and their Implementations
Kashif Aleem
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 

Similar to Pellucid stm (20)

SF Scala meet up, lighting talk: SPA -- Scala JDBC wrapper
SF Scala meet up, lighting talk: SPA -- Scala JDBC wrapperSF Scala meet up, lighting talk: SPA -- Scala JDBC wrapper
SF Scala meet up, lighting talk: SPA -- Scala JDBC wrapper
 
Data in Motion: Streaming Static Data Efficiently 2
Data in Motion: Streaming Static Data Efficiently 2Data in Motion: Streaming Static Data Efficiently 2
Data in Motion: Streaming Static Data Efficiently 2
 
Scott Anderson [InfluxData] | InfluxDB Tasks – Beyond Downsampling | InfluxDa...
Scott Anderson [InfluxData] | InfluxDB Tasks – Beyond Downsampling | InfluxDa...Scott Anderson [InfluxData] | InfluxDB Tasks – Beyond Downsampling | InfluxDa...
Scott Anderson [InfluxData] | InfluxDB Tasks – Beyond Downsampling | InfluxDa...
 
Implementing STM in Java
Implementing STM in JavaImplementing STM in Java
Implementing STM in Java
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 
.Net Enterprise Services and their Implementations
.Net Enterprise Services and their Implementations.Net Enterprise Services and their Implementations
.Net Enterprise Services and their Implementations
 
Reactive Summit 2017
Reactive Summit 2017Reactive Summit 2017
Reactive Summit 2017
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
 
Concurrent Application Development using Scala
Concurrent Application Development using ScalaConcurrent Application Development using Scala
Concurrent Application Development using Scala
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional Programming
 
Clojure functions examples
Clojure functions examplesClojure functions examples
Clojure functions examples
 
Serverless stateful
Serverless statefulServerless stateful
Serverless stateful
 
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
 
The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212The Ring programming language version 1.10 book - Part 54 of 212
The Ring programming language version 1.10 book - Part 54 of 212
 
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
WebCamp:Front-end Developers Day. Александр Мостовенко "Rx.js - делаем асинхр...
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
Hidden Gems in Swift
Hidden Gems in SwiftHidden Gems in Swift
Hidden Gems in Swift
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

Pellucid stm

  • 2. Alternative to lock-based synchronization Analogous to database transactions ACI (ACID with out the „D‟) Simple! (well… simplier) WHAT IS STM?
  • 3. libraryDependencies += ("org.scala-stm" %% "scala-stm" % "0.7") import scala.concurrent.stm._ val protectedInt = Ref(0) atomic{ implicit transaction=> val currentValue = protectedInt.get protectedInt.set(currentValue + 1) } WHAT DOES IT LOOK LIKE?
  • 4. ATOMIC val protectedInt = Ref(0) val anotherProtectedInt = Ref(0) atomic{ implicit transaction => val currentValue = protectedInt.get protectedInt.set(currentValue + 1) val anotherCurrentValue = anotherProtectedInt.get anotherProtectedInt.set(anotherCurrentValue + 1) }
  • 5. CONSISTENT val protectedInt = Ref(0) atomic{ transaction => val currentValue = protectedInt.get(transaction) protectedInt.set(currentValue + 1)(transaction) }
  • 6. val protectedInt = Ref(0) atomic{ implicit transaction => val currentValue = protectedInt.get protectedInt.set(currentValue + 1) } ISOLATED
  • 7. STM is not Durable DURABLE
  • 8. ADVANTAGES: DEADLOCK / LIVELOCK val protectedInt = Ref(0) atomic{ implicit transaction => val currentValue = protectedInt.get protectedInt.set(currentValue + 1) }
  • 9. ADVANTAGES: PRIORITY INVERSION val protectedInt = Ref(0) atomic{ implicit transaction => val currentValue = protectedInt.get protectedInt.set(currentValue + 1) }
  • 10. ADVANTAGES: COMPOSABILITY val protectedInt = Ref(0) val anotherProtedtedInt = Ref(0) atomic{ implicit transaction => val currentValue = protectedInt.get protectedInt.set(currentValue + 1) atomic{ implicit transaction => val anotherCurrentValue = anotherProtectedInt.get val anotherProctedInt.set(anotherCurrentValue + 1) } }
  • 11. GOTCHAS: IMMUTABILITY! // bad! val badMap= Ref(new java.util.HashMap[String, Int]()) val mutableMap = atomic{ implicit transaction => badMap.get } mutableMap.put(“Wrong!”, 666) // good val goodMap = Ref(Map(“Good” -> 7)) atomic{ implicit transaction => val tempMap = goodMap.get goodMap.set(tempMap + (“Good” -> 777)) }
  • 12. GOTCHAS: REFERENTIAL TRANSPARENCY //bad val protectedString = Ref("This is a string") val time = System.currentTimeMillis atomic{ implicit transaction => if(time % 2 == 0) protectedString.set("Time was even") else protectedString.set("Time was odd") } //good atomic{ implicit transaction => val time = System.currentTimeMillis if(time % 2 == 0) protectedString.set("Time was even") else protectedString.set("Time was odd") }
  • 13. EXTENDED EXAMPLE: STM case class Account(number: Int, balance: Int) val accounts = Ref(Map( 1 -> Account(1, 100), 2 -> Account(2, 100) )) def transfer(to: Int, from: Int, amount: Int){ atomic{ implicit transaction => val map = accounts.get val toAccount = map(to) val fromAccount = map(from) accounts.set( map + (to -> (toAccount.copy(balance = toAccount.balance + amount))) + (from -> (fromAccount.copy(balance = fromAccount.balance - amount))) ) } }
  • 14. EXTENDED EXAMPLE: SYNCHRONIZED import java.util._ private val accounts = new HashMap[Int, Account]() accounts.put(1, Account(1, 100)) accounts.put(2, Account(2, 100)) def transfer(to: Int, from: Int, amount: Int){ accounts.synchronized{ val toAccount = accounts.get(to) val fromAccount = accounts.get(from) accounts.put(to, (toAccount.copy(balance = toAccount.balance + amount))) accounts.put(from, (fromAccount.copy(balance = fromAccount.balance - amount))) } }
  • 15. EXTENDED EXAMPLE: SYNCHRONIZED2 import java.util.concurrent._ private val accounts = ConcurrentHashMap[Int, Account]() accounts.put(1, Account(1, 100)) accounts.put(2, Account(2, 100)) def transfer(to: Int, from: Int, amount: Int){ val toAccount = accounts.get(to) val fromAccount = accounts.get(from) toAccount.synchronized{ fromAccount.synchronized{ accounts.put(to, (toAccount.copy(balance = toAccount.balance + amount))) accounts.put(from, (fromAccount.copy(balance = fromAccount.balance - amount))) } } }
  • 16. EXTENDED EXAMPLE: SYNCHRONIZED3 import java.util.concurrent._ private val accounts = ConcurrentHashMap[Int, Account]() accounts.put(1, Account(1, 100)) accounts.put(2, Account(2, 100)) def transfer(to: Int, from: Int, amount: Int){ val toAccount = accounts.get(to) val fromAccount = accounts.get(from) val (firstLock, secondLock) = if(to > from) (toAccount, fromAccount) else (fromAccount, toAccount) firstLock.synchronized{ secondLock.synchronized{ accounts.put(to, (toAccount.copy(balance = toAccount.balance + amount))) accounts.put(from, (fromAccount.copy(balance = fromAccount.balance - amount))) } } }

Editor's Notes

  1. Hello, I'm Dustin Whitney. I'm one of the organizers of the New York ScalaMeetup, and I'm the CTO of Pellucid Analytics. We're hiring. This talk is about Software Transactional Memory (STM). I feel that in the Scala world STM gets less attention than it deserves, which is odd given it's popularity in other programming languages, and I honestly think it's a great first choice when attacking concurrency issues with Scala. So I felt it would be worthwhile to give a lightning talk about it, especially given how simple it is. In fact 30 minutes is probably too much time. -- let's get started
  2. What is STM? It's an alternative to lock-based synchronization, which has been the standard for doing concurrency in Java since its inception. STM is analagous to database transactions in that when a transaction is started, the ACID properties are adheared to, with the acception of the 'D' in ACID. I'll get back to what the ACID properties and how they are manifested in STM in later slides, but it suffices to say that this is a good thing. Also, STM is simple and easy to reason about. What does it look like in Scala?
  3. Eventually STM will be included in the Scala Standard Library, but for now you must include it as a dependency in your sbt build file.This is the import statement, and after you've imported it, there are really only two things you need to know:1. There is a 'Ref', which protects a piece of shared memory. In this case it is protecting an Integer.2. To access the shared memory protected by the 'Ref', you must be inside of an atomic block, where a transaction is created. When you're inside of the atomic block you can access the shared memory with the get method and modify the shared memory with the set method.
  4. Actions taken within the atomic block are 'atomic', the 'A' from ACID. Being atomic means that the actions inside of the block are 'all or nothing', meaning if any part of an atomic block fails in committing a successful transaction, then none of the values in a Ref will be updated. The example I have here shows two Refs. It's possible during the execution of this block, one or both of the Refs could be updated by another thread before the block is done executing. Should this occur, no change to either Ref will occur, and the atomic block will then retry.Something should be said about retries. How is it determined that a success or failure has occurred? STM uses optimistic concurrency control. What that means is, from a high level, when a block is executed a transaction object is created with a unique number related to the state of the Ref. At the end of the block an attempt to commit is made, and if the number of the transaction does not match the current state of the Ref, the transaction is a failure, and the atomic block is retried. Retries will occur until either a success occurs or too many retries occurs. The 'too many retries' number is configurable.
  5. Picking up from there, atomic blocks are consistent, the 'C' in ACID. Your transaction acts as a way to always retrieve the same state of the world throughout your transaction. In this example, I've removed the implicit keyword from the front of the transaction and passed it into the get and set methods manually to make explicit the fact that it is used to fetch a consistent view of the world. It would not be good if another thread were to update the ref and when fetching it you were fetching those changes, which leads to the next letter in ACID
  6. modifications to the Ref are isolated from the rest of the world until a successful commit is made. also when a successful commit is made those changes will not be visible to transactions that began before the successful commit.
  7. STM is not durable since it is protecting memory, which is inherently non-durable.
  8. To make clear some of the advantages of STM over lock-based synchronization, I thought I'd highlight a few things.STM does not suffer from deadlock or livelock, because there are no locks. To explain what deadlock is, imagine a process that much obtain two locks. One thread has one lock and another thread has the other, and both are waiting for the other to release the lock so they can continue processing. They will continue to wait until the program is terminated. With STM, you simply start a transaction, and go. If something goes wrong, the atomic block will execute again.
  9. Another disadvantage of lock-based synchronization is priority inversion. This happens when lots of low priority threads take ahold of a lock and keep a high priority thread blocking. Again, since there are no locks with STM, high priority threads can gain access to the shared resource at will. It should be noted that with STM there can be issues with competition over committing transactions, but resolving these issues are pretty easy since they are easy to track down and debug.
  10. I think the biggest advantage STM has over lock-based synchronization is composability. Locks simply don't compose. Locks are chosen more or less arbitrarily, and when you wish to have multiple parts of a program work together in a threadsafe manner where locks are involved, you must know what all of the locks are, and what their policies are, and it's really tough to make happen. With STM, you can nest atomic blocks, and everything works out the way you'd expect.
  11. Can you find the errors?
  12. Can you find the errors?