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

Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJSKyung Yeol Kim
 
Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223Jarmo van de Seijp Shadbox ERC223
Jarmo van de Seijp Shadbox ERC223Jarmo van de Seijp
 
Ejercicios
EjerciciosEjercicios
Ejerciciosleonharo
 
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 Streamsmattpodwysocki
 
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 archaeologistyoavrubin
 
Designing a database like an archaeologist
Designing a database like an archaeologistDesigning a database like an archaeologist
Designing a database like an archaeologistyoavrubin
 
Programação assíncrona utilizando Coroutines
Programação assíncrona utilizando CoroutinesProgramação assíncrona utilizando Coroutines
Programação assíncrona utilizando CoroutinesDiego Gonçalves Santos
 
Pivorak Clojure by Dmytro Bignyak
Pivorak Clojure by Dmytro BignyakPivorak Clojure by Dmytro Bignyak
Pivorak Clojure by Dmytro BignyakPivorak MeetUp
 
“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...DevClub_lv
 
Using spark data frame for sql
Using spark data frame for sqlUsing spark data frame for sql
Using spark data frame for sqlDaeMyung Kang
 
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 ArchitectureFabio Collini
 
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 Coroutinestdc-globalcode
 
Javascript Arrays
Javascript ArraysJavascript Arrays
Javascript Arraysshaheenakv
 
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 202Mahmoud Samir Fayed
 
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 30Mahmoud Samir Fayed
 
Mozilla とブラウザゲーム
Mozilla とブラウザゲームMozilla とブラウザゲーム
Mozilla とブラウザゲームNoritada Shimizu
 
Monadologie
MonadologieMonadologie
Monadologieleague
 

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

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 wrapperChester Chen
 
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 2Martin Zapletal
 
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...InfluxData
 
Implementing STM in Java
Implementing STM in JavaImplementing STM in Java
Implementing STM in JavaMisha Kozik
 
.Net Enterprise Services and their Implementations
.Net Enterprise Services and their Implementations.Net Enterprise Services and their Implementations
.Net Enterprise Services and their ImplementationsKashif Aleem
 
Reactive Summit 2017
Reactive Summit 2017Reactive Summit 2017
Reactive Summit 2017janm399
 
(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
 
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 ScalaSiarhiej Siemianchuk
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingSergey Shishkin
 
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."sjabs
 
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 212Mahmoud Samir Fayed
 
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 - делаем асинхр...GeeksLab Odessa
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }John De Goes
 
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 risksSeniorDevOnly
 
Hidden Gems in Swift
Hidden Gems in SwiftHidden Gems in Swift
Hidden Gems in SwiftNetguru
 

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

Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 

Recently uploaded (20)

Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 

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?