SlideShare a Scribd company logo
Concurrency Patterns David Kemp Melbourne Patterns Group March 2010 Some rights reserved:  Creative Commons Attribution-Noncommercial-Share Alike http://creativecommons.org/licenses/by-nc-sa/3.0/
Concurrency: what and why?
Thread Thread Stack Code Heap Stack
Issues
Race Conditions public class BankAccount { private int balance; public void adjustBalance(int amount) { balance = balance + amount; } ... }
Memory Consistency (A) Initially Thread B Instructions may be re-ordered a = true; b = true; return !b | a; boolean a = false; boolean b = false; Thread A Possible for Thread B to see  b  as true before  a  is true.
Memory Consistency (B) Initially Thread B Partially constructed objects can be visible object = new MyClass(); if (object != null) object.doSomething(); MyClass object = null; Thread A object  may not be in a consistent state in thread B
If Possible: Avoid Concurrency!!
Concurrency Primitives
Threads (in Java) Runnable runnable = new MyRunnable();  Thread thread = new Thread(runnable); thread.start(); interface Runnable { void run(); } Looks strangely like the command pattern (covered last month). The Java ExecutorService interface is even more like the Command Pattern.
Mutex (Mutual Exclusion Lock)
Mutexes can fix race conditions public class BankAccount { Object lock = new Object(); int balance; public void adjustBalance(int amount) { synchronize(lock)  { balance = balance + amount; } }
Mutexes can fix Memory Consistency Initially Thread B synchronize(lock) {  a = true; b = true; } synchronize(lock) {  return !b | a; } Object lock = new Object(); boolean a = false; boolean b = false; Thread A Must use the same lock! Can also fix some memory consistency problems using the volatile keyword.
If you need clever analysis to show thread safety, then it is either broken now, or will be broken by some future maintainer!!!!
Other Concurrency Abstractions Condition Variables Semaphores. Latches. Barriers. Futures. Read/Write Locks. Blocking Queues. Exchangers. Threadpools. Atomic Compare-And-Set
Some Patterns
Fully Synchronized Objects Photo by Kevin Hamm. Some rights reserved. See:  http://www.flickr.com/photos/krhamm/171302278/in/set-72157594171880205/
Fully Synchronized Object All methods on a fully synchronized object are synchronized on a single lock.
Resource Ordering Image by  Benjamin D. Esham for the Wikimedia Commons. Some rights reserved. See:  http://en.wikipedia.org/wiki/File:Dining_philosophers.png/
Copy-on-write
Passing immutable objects as messages between threads. Concurrent modification ceases to be a problem!
Partitioning
Double Check Locking Used for lazy initialization Photo by Kirainet. Some rights reserved. See:  http://www.flickr.com/photos/torek/2467519466/
Double Check Locking Easy to stuff up!!!
Double Check Locking Was not possible in Java before 1.5. Locks have become cheap, and so double-check not so useful. Usually better to use static initialization anyway. Was unreliable in C++/Posix threads when I last looked. Find out if it works in your language/platform before using!!
Double Check Locking But it is a nice demonstration of some concurrency issues
Double check locking (Warning: did not work before Java 1.5) volatile  Properties properties = null; final Object lock = new Object(); public Properties getProperties() { if (properties == null) { synchronized  (lock) { if (properties == null) { tmp = new Properties(); tmp.load(inputStream); properties = tmp; } } } return properties; } Possibly broken! Definitely Brittle!
Lock-free Queue
Lock Free Queue Queue Dummy Node Real Head Node Tail Penultimate node Head Tail : Might point to last or second last node! References are all updated using the Atomic Test-And-Set.
References M. Ben-Ari,  Principles of Concurrent Programming,  Prentice Hall. Doug Lea,  Concurrent Programming in Java Second Edition. Design Principles and Patterns , Addison-Wesley. Brian Goetz,  Java Concurrency in Practice . Pearson Education. Software Engineering Radio, Episodes 12, 19, and 29. http://www.se-radio.net/

More Related Content

PPTX
Concurrency: how to shoot yourself in both feet. Simultaneously.
Victor Haydin
 
PPTX
Fork Join
Dmitry Buzdin
 
PDF
RxJava@DAUG
Maxim Volgin
 
PDF
Mobile Software Engineering Crash Course - C02 Java Primer
Mohammad Shaker
 
ODP
Objective-C: Good and Bad
Anthony Shoumikhin
 
PDF
Fork Join (BeJUG 2012)
Sander Mak (@Sander_Mak)
 
PPTX
Introduction to modern c++ principles(part 1)
Oky Firmansyah
 
PDF
Ruby Gotchas
Dave Aronson
 
Concurrency: how to shoot yourself in both feet. Simultaneously.
Victor Haydin
 
Fork Join
Dmitry Buzdin
 
RxJava@DAUG
Maxim Volgin
 
Mobile Software Engineering Crash Course - C02 Java Primer
Mohammad Shaker
 
Objective-C: Good and Bad
Anthony Shoumikhin
 
Fork Join (BeJUG 2012)
Sander Mak (@Sander_Mak)
 
Introduction to modern c++ principles(part 1)
Oky Firmansyah
 
Ruby Gotchas
Dave Aronson
 

What's hot (17)

PPTX
Gdg dev fest 2107 to kotlin, with love
Ayman Mahfouz
 
PPTX
Exploring Kotlin language basics for Android App development
Jayaprakash R
 
DOCX
A JavaScript Master Class - From the Wows to the WTFs
Shahriar Hyder
 
ODP
ooc - A hybrid language experiment
Amos Wenger
 
PDF
Little Did He Know ...
Burt Beckwith
 
PDF
Twins: OOP and FP
RichardWarburton
 
PDF
Cpp17 and Beyond
ComicSansMS
 
PPT
An introduction to javascript
MD Sayem Ahmed
 
PPTX
oojs
Imran shaikh
 
PPTX
Groovy / comparison with java
Liviu Tudor
 
PDF
Assign
EMSNEWS
 
PPTX
Asynchronous Programming in .NET
Pierre-Luc Maheu
 
PDF
API Design
Tim Boudreau
 
PPTX
JS Fest 2018. Douglas Crockford. The Better Parts
JSFestUA
 
PDF
Threads and Java Memory Model Explained
Luiz Fernando Teston
 
PDF
Frege Tutorial at JavaOne 2015
Dierk König
 
Gdg dev fest 2107 to kotlin, with love
Ayman Mahfouz
 
Exploring Kotlin language basics for Android App development
Jayaprakash R
 
A JavaScript Master Class - From the Wows to the WTFs
Shahriar Hyder
 
ooc - A hybrid language experiment
Amos Wenger
 
Little Did He Know ...
Burt Beckwith
 
Twins: OOP and FP
RichardWarburton
 
Cpp17 and Beyond
ComicSansMS
 
An introduction to javascript
MD Sayem Ahmed
 
Groovy / comparison with java
Liviu Tudor
 
Assign
EMSNEWS
 
Asynchronous Programming in .NET
Pierre-Luc Maheu
 
API Design
Tim Boudreau
 
JS Fest 2018. Douglas Crockford. The Better Parts
JSFestUA
 
Threads and Java Memory Model Explained
Luiz Fernando Teston
 
Frege Tutorial at JavaOne 2015
Dierk König
 
Ad

Similar to Concurrency Patterns (20)

PPTX
Ruby Blocks
Sarah Allen
 
PPTX
chap 8 : The java.lang and java.util Packages (scjp/ocjp)
It Academy
 
PDF
Latest C++ Interview Questions and Answers
DaisyWatson5
 
DOCX
Jist of Java
Nikunj Parekh
 
DOCX
JAVA CONCEPTS AND PRACTICES
Nikunj Parekh
 
PPTX
Weird Javascript Weekends first session presentaion
SrishtyMangutte
 
ODP
jsbasics-slide
Peter Borkuti
 
PPTX
Advanced Introduction to Java Multi-Threading - Full (chok)
choksheak
 
PPTX
Ruby Blocks
Sarah Allen
 
PDF
Wade Not in Unknown Waters. Part Four.
Andrey Karpov
 
PDF
Javascript
Aditya Gaur
 
PPS
Master in javascript
Robbin Zhao
 
PDF
Lockless
Sandeep Joshi
 
PPTX
Java tutorial part 4
Mumbai Academisc
 
ODP
Advanced java
Giacomo Veneri
 
PDF
Wade Not in Unknown Waters. Part Four.
PVS-Studio
 
PDF
C++ interview questions
arjavi
 
PPT
Ajax and JavaScript Bootcamp
AndreCharland
 
PDF
[A 3]Javascript oop for xpages developers - public
Kazunori Tatsuki
 
PPTX
Joshua bloch effect java chapter 3
Kamal Mukkamala
 
Ruby Blocks
Sarah Allen
 
chap 8 : The java.lang and java.util Packages (scjp/ocjp)
It Academy
 
Latest C++ Interview Questions and Answers
DaisyWatson5
 
Jist of Java
Nikunj Parekh
 
JAVA CONCEPTS AND PRACTICES
Nikunj Parekh
 
Weird Javascript Weekends first session presentaion
SrishtyMangutte
 
jsbasics-slide
Peter Borkuti
 
Advanced Introduction to Java Multi-Threading - Full (chok)
choksheak
 
Ruby Blocks
Sarah Allen
 
Wade Not in Unknown Waters. Part Four.
Andrey Karpov
 
Javascript
Aditya Gaur
 
Master in javascript
Robbin Zhao
 
Lockless
Sandeep Joshi
 
Java tutorial part 4
Mumbai Academisc
 
Advanced java
Giacomo Veneri
 
Wade Not in Unknown Waters. Part Four.
PVS-Studio
 
C++ interview questions
arjavi
 
Ajax and JavaScript Bootcamp
AndreCharland
 
[A 3]Javascript oop for xpages developers - public
Kazunori Tatsuki
 
Joshua bloch effect java chapter 3
Kamal Mukkamala
 
Ad

More from melbournepatterns (20)

PDF
An Introduction to
melbournepatterns
 
PPT
State Pattern from GoF
melbournepatterns
 
PDF
Iterator Pattern
melbournepatterns
 
PDF
Iterator
melbournepatterns
 
PPTX
Continuous Integration, Fast Builds and Flot
melbournepatterns
 
PPTX
Command Pattern
melbournepatterns
 
PPTX
Code Contracts API In .Net
melbournepatterns
 
PPTX
LINQ/PLINQ
melbournepatterns
 
PDF
Gpu Cuda
melbournepatterns
 
PPTX
Facade Pattern
melbournepatterns
 
PPT
Phani Kumar - Decorator Pattern
melbournepatterns
 
PPT
Composite Pattern
melbournepatterns
 
PPT
Adapter Design Pattern
melbournepatterns
 
PPT
Prototype Design Pattern
melbournepatterns
 
PPT
Factory Method Design Pattern
melbournepatterns
 
PPT
Abstract Factory Design Pattern
melbournepatterns
 
PPT
A Little Lisp
melbournepatterns
 
PPT
State Pattern in Flex
melbournepatterns
 
PPT
Active Object
melbournepatterns
 
PPT
Extract Composite Talk Andy
melbournepatterns
 
An Introduction to
melbournepatterns
 
State Pattern from GoF
melbournepatterns
 
Iterator Pattern
melbournepatterns
 
Continuous Integration, Fast Builds and Flot
melbournepatterns
 
Command Pattern
melbournepatterns
 
Code Contracts API In .Net
melbournepatterns
 
LINQ/PLINQ
melbournepatterns
 
Facade Pattern
melbournepatterns
 
Phani Kumar - Decorator Pattern
melbournepatterns
 
Composite Pattern
melbournepatterns
 
Adapter Design Pattern
melbournepatterns
 
Prototype Design Pattern
melbournepatterns
 
Factory Method Design Pattern
melbournepatterns
 
Abstract Factory Design Pattern
melbournepatterns
 
A Little Lisp
melbournepatterns
 
State Pattern in Flex
melbournepatterns
 
Active Object
melbournepatterns
 
Extract Composite Talk Andy
melbournepatterns
 

Recently uploaded (20)

PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
Architecture of the Future (09152021)
EdwardMeyman
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Doc9.....................................
SofiaCollazos
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Architecture of the Future (09152021)
EdwardMeyman
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 

Concurrency Patterns

  • 1. Concurrency Patterns David Kemp Melbourne Patterns Group March 2010 Some rights reserved: Creative Commons Attribution-Noncommercial-Share Alike http://creativecommons.org/licenses/by-nc-sa/3.0/
  • 3. Thread Thread Stack Code Heap Stack
  • 5. Race Conditions public class BankAccount { private int balance; public void adjustBalance(int amount) { balance = balance + amount; } ... }
  • 6. Memory Consistency (A) Initially Thread B Instructions may be re-ordered a = true; b = true; return !b | a; boolean a = false; boolean b = false; Thread A Possible for Thread B to see b as true before a is true.
  • 7. Memory Consistency (B) Initially Thread B Partially constructed objects can be visible object = new MyClass(); if (object != null) object.doSomething(); MyClass object = null; Thread A object may not be in a consistent state in thread B
  • 8. If Possible: Avoid Concurrency!!
  • 10. Threads (in Java) Runnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); thread.start(); interface Runnable { void run(); } Looks strangely like the command pattern (covered last month). The Java ExecutorService interface is even more like the Command Pattern.
  • 12. Mutexes can fix race conditions public class BankAccount { Object lock = new Object(); int balance; public void adjustBalance(int amount) { synchronize(lock) { balance = balance + amount; } }
  • 13. Mutexes can fix Memory Consistency Initially Thread B synchronize(lock) { a = true; b = true; } synchronize(lock) { return !b | a; } Object lock = new Object(); boolean a = false; boolean b = false; Thread A Must use the same lock! Can also fix some memory consistency problems using the volatile keyword.
  • 14. If you need clever analysis to show thread safety, then it is either broken now, or will be broken by some future maintainer!!!!
  • 15. Other Concurrency Abstractions Condition Variables Semaphores. Latches. Barriers. Futures. Read/Write Locks. Blocking Queues. Exchangers. Threadpools. Atomic Compare-And-Set
  • 17. Fully Synchronized Objects Photo by Kevin Hamm. Some rights reserved. See: http://www.flickr.com/photos/krhamm/171302278/in/set-72157594171880205/
  • 18. Fully Synchronized Object All methods on a fully synchronized object are synchronized on a single lock.
  • 19. Resource Ordering Image by Benjamin D. Esham for the Wikimedia Commons. Some rights reserved. See: http://en.wikipedia.org/wiki/File:Dining_philosophers.png/
  • 21. Passing immutable objects as messages between threads. Concurrent modification ceases to be a problem!
  • 23. Double Check Locking Used for lazy initialization Photo by Kirainet. Some rights reserved. See: http://www.flickr.com/photos/torek/2467519466/
  • 24. Double Check Locking Easy to stuff up!!!
  • 25. Double Check Locking Was not possible in Java before 1.5. Locks have become cheap, and so double-check not so useful. Usually better to use static initialization anyway. Was unreliable in C++/Posix threads when I last looked. Find out if it works in your language/platform before using!!
  • 26. Double Check Locking But it is a nice demonstration of some concurrency issues
  • 27. Double check locking (Warning: did not work before Java 1.5) volatile Properties properties = null; final Object lock = new Object(); public Properties getProperties() { if (properties == null) { synchronized (lock) { if (properties == null) { tmp = new Properties(); tmp.load(inputStream); properties = tmp; } } } return properties; } Possibly broken! Definitely Brittle!
  • 29. Lock Free Queue Queue Dummy Node Real Head Node Tail Penultimate node Head Tail : Might point to last or second last node! References are all updated using the Atomic Test-And-Set.
  • 30. References M. Ben-Ari, Principles of Concurrent Programming, Prentice Hall. Doug Lea, Concurrent Programming in Java Second Edition. Design Principles and Patterns , Addison-Wesley. Brian Goetz, Java Concurrency in Practice . Pearson Education. Software Engineering Radio, Episodes 12, 19, and 29. http://www.se-radio.net/

Editor's Notes

  • #3: Processes and threads. Multiple cpu’s. IO. Responsiveness.
  • #7: Can be re-ordered by compiler, JVM, or caching effects.