SlideShare a Scribd company logo
Java Concurrency
Basic Thread Synchronization
zxholy@gmail.com
In this chapter, we will cover:
● Synchronizing a method
● Arranging independent attributes in
synchronized classes
● Using conditions in synchronized code
● Synchronizing a block of code with a Lock
● Synchronizing data access with read/write
locks
● Modifying Lock fairness
● Using multiple conditions in a Lock
Introduction
● Critical section
A critical section is a block of code that
accesses a shared resource and can't be
executed by more than one thread at the same
time.
Introduction
● Synchronization mechanisms
When a thread wants access to a critical section, it uses
one of those synchronization mechanisms to find out if
there is any other thread executing the critical section.
If not, the thread enters the critical section.
Otherwise, the thread is suspended by the
synchronization mechanism until the thread that is
executing the critical section ends it.
When more than one thread is waiting for a thread to
finish the execution of a critical section, the JVM chooses
one of them, and the rest wait for their turn.
Introduction
Two basic synchronization mechanisms:
● The keyword synchronized
● The Lock interface and its implementations
Synchronizing a method
Every method declared with the
synchronized keyword is a critical section
and Java only allows the execution of one of
the critical sections of an object.
Static methods have a different behavior. Two
threads can access two different
synchronized methods if one is static and
the other one is not.
We will have a bank account and two threads;
one that transfers money to the account and
another one that withdraws money from the
account.
Synchronization mechanisms ensures that
the final balance of the account will be correct.
How to do it…
Create a class called: Account
One attribute: private double amount;
Two method:
addAmount() substractAmount();
Two class: Bank and Company
[Java concurrency]02.basic thread synchronization
How it works...
When remove synchronized keyword.
The order of execution of the threads is not
guaranteed by the JVM.
Using the synchronized keyword, we
guarantee correct access to shared data in
concurrent applications.
There is more...
The synchronized keyword penalizes the
performance of the application, so you must
only use it on methods that modify shared data
in a concurrent environment.
You can use recursive calls with
synchronized methods.
We can use the synchronized keyword to
protect the access to a block of code instead of
an entire method.
Arranging independent attributes in
synchronized classes
When executing the synchronized method
which you use the this keyword as a
parameter, you can only use other object
references.
But, now...
● Two independent attributes, synchronize the
access to each variable.
● One thread accessing one attribute, another
thread accessing another one.
Simulates a cinema with two screens and two
ticket offices.
When a ticket office sells tickets, they are for
one of the two cinemas, but not for both.
So the numbers of free seats in each cinema
are independent attributes.
How to do it...
Cinema class:
Two methods:
Two ticket-office:
[Java concurrency]02.basic thread synchronization
How it works...
When you use an object as a parameter of
synchronized method, JVM guarantees that:
Only one thread can have access to all the
blocks of code protected with that object.
Note: objects, not classes.
We have two objects that controls access to the
vacanciesCinema1 attribute and
vacanciesCinema2 attribute separately.
One thread can modify one attribute each time.
Using conditions in synchronized
code
Producer-consumer problem:
A classic problem in concurrent programming.
● A data buffer
○ A shared data structure
● One or more producers
○ Can’t save data in the buffer if it’s full
● One or more consumers
○ Can’t take data from the buffer if it’s empty
Java provides the wait(), notify() and
notifyAll() method s implemented in the
Object class.
wait() method
Called by a thread, inside a synchronized
block of code (Outside, JVM throws an
IllegalMonitorStateException
exception).
The JVM puts the thread to sleep and releases
the resources.
To wake up the thread, you must call the
notify() or notifyAll() method inside a
block of code protected by the same object.
Implement the producer-consumer problem
using the synchronized keyword and the
wait(), notify(), and notifyAll()
methods.
How to do it...
EventStorage class:
set() method:
get() method:
Producer and Consumer class:
Main class:
How it works...
[Java concurrency]02.basic thread synchronization
Synchronizing a block of code with a
Lock
Another mechanism for the synchronization of
blocks of code.
Based on Lock interface and classes that
implement it (as ReentrantLock).
Compare Lock and synchronized
● The mechanism based on Lock interface is
more flexible.
● The Lock interfaces provide additional
functionalities, as tryLock().
● Allow a separation of read and write
operations having multiple readers and only
one modifier.
● Better performance
Using the Lock interface and the
ReentrantLock class that implements it,
implementing a program that simulates a print
queue.
How to do it...
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
How it works...
There’s more...
tryLock() method returns a boolean value,
true if the thread gets the control of the lock,
and false if not.
The ReentrantLock class also allows the use
of recursive calls.
Avoid deadlocks.
Situation: Two or more threads are blocked
waiting for locks that never will be unlocked.
Reason: Both threads try to get the locks in the
opposite order.
Modifying Lock fairness
The constructor of the ReentrantLock and
ReentrantReadWriteLock classes admits a
boolean parameter named fair:
false: non-fair mode
selects one without any criteria.
true: fair mode
How to do it...
Job class
[Java concurrency]02.basic thread synchronization
main() method:
How it works...
fair: true
fair: false
fair: false
Synchronizing data access with
read/write locks
One of the most significant improvements
offered by locks is the ReadWriteLock
interface and the ReentrantReadWriteLock
class, the unique one that implements it.
Two locks: read/write
Use ReadWriteLock to control the access to
an object that stores the prices of two products.
How to do it...
PricesInfo class:
getPrice1() setPrice()
Reader class:
Writer class:
main() method:
How it works...
Ensure the correct use of these locks, using
them with the same purposes.
When you get the read lock of a Lock
interface, you can’t modify the calue of the
variable.
Using multiple conditions in a Lock
A lock may be associated with one or more
conditions. These conditions are declared in
the Condition interface.
The Condition interface provides the
mechanisms to suspend a thread and to wake
up a suspended thread.
Condition
● Synchronized + monitor methods(wait,
notify and notifyAll)
● Lock + Condition
To obtain a Condition instance for a
particular Lock instance use its
newCondition() method.
Producer-consumer problem.
We have a data buffer, one or more producers
of data that save it in the buffer, and one or
more consumers of data that take it from the
buffer as explained earlier in this chapter
How to do it...
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
How it works...
When a thread calls the await() method of a
condition, it automatically frees the control of
the lock, so that another thread can get it and
begin the execution of the same, or another
critical section protected by that lock.
You must be careful with the use of await()
and signal().
You can use conditions with the ReadLock and
WriteLock locks of a read/write lock.
End
Thank you!

More Related Content

PPT
Java Performance, Threading and Concurrent Data Structures
PPT
Thread
PDF
Java Thread Synchronization
PDF
[Java concurrency]01.thread management
PPT
Synchronization.37
PPTX
Advanced Introduction to Java Multi-Threading - Full (chok)
PDF
javathreads
PDF
Programming with Threads in Java
Java Performance, Threading and Concurrent Data Structures
Thread
Java Thread Synchronization
[Java concurrency]01.thread management
Synchronization.37
Advanced Introduction to Java Multi-Threading - Full (chok)
javathreads
Programming with Threads in Java

What's hot (20)

PPT
Java multi threading
PDF
Java threading
PDF
Multithreading in Java
PPTX
Multithreading in java
ODP
Multithreading In Java
PDF
Java Concurrency in Practice
PPTX
Multithread Programing in Java
PPTX
Thread model of java
PPTX
Basics of Java Concurrency
PDF
Java Course 10: Threads and Concurrency
PPT
Learning Java 3 – Threads and Synchronization
PDF
Threads concept in java
PPT
Java Multithreading and Concurrency
PPT
Java concurrency
PPT
Threads in Java
PPT
Thread model in java
PPTX
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
PPT
Basic of Multithreading in JAva
PPT
Java Threads and Concurrency
PPTX
Threading in java - a pragmatic primer
Java multi threading
Java threading
Multithreading in Java
Multithreading in java
Multithreading In Java
Java Concurrency in Practice
Multithread Programing in Java
Thread model of java
Basics of Java Concurrency
Java Course 10: Threads and Concurrency
Learning Java 3 – Threads and Synchronization
Threads concept in java
Java Multithreading and Concurrency
Java concurrency
Threads in Java
Thread model in java
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Basic of Multithreading in JAva
Java Threads and Concurrency
Threading in java - a pragmatic primer
Ad

Viewers also liked (20)

PDF
Closures: The Next "Big Thing" In Java
PDF
Intro to Java 8 Closures (Dainius Mezanskas)
PDF
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)
PDF
如何更好地设计测试用例-BQConf
PDF
大型网站架构演变
ODP
Building a lock profiler on the JVM
PPT
Recipe 黃佳伶 葉愛慧
PDF
Java多线程技术
PDF
Save JVM by Yourself: Real War Experiences of OOM
PPT
Lock Interface in Java
PDF
Nginx+tomcat https 配置
PDF
PDF
App开发过程的演变之路
PDF
浅谈项目管理(诸葛B2B电商研发部版改)
PDF
Implementing STM in Java
PPTX
Thrift+scribe实现分布式日志收集,并与log4j集成
PDF
Performance Tuning - Understanding Garbage Collection
PDF
Concurrency: Best Practices
PDF
JVM及其调优
PPTX
Java concurrency - Thread pools
Closures: The Next "Big Thing" In Java
Intro to Java 8 Closures (Dainius Mezanskas)
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)
如何更好地设计测试用例-BQConf
大型网站架构演变
Building a lock profiler on the JVM
Recipe 黃佳伶 葉愛慧
Java多线程技术
Save JVM by Yourself: Real War Experiences of OOM
Lock Interface in Java
Nginx+tomcat https 配置
App开发过程的演变之路
浅谈项目管理(诸葛B2B电商研发部版改)
Implementing STM in Java
Thrift+scribe实现分布式日志收集,并与log4j集成
Performance Tuning - Understanding Garbage Collection
Concurrency: Best Practices
JVM及其调优
Java concurrency - Thread pools
Ad

Similar to [Java concurrency]02.basic thread synchronization (20)

PDF
22 multi threading iv
PPTX
Thread syncronization
DOC
Concurrency Learning From Jdk Source
PPTX
Concurrency
PPT
Reliable and Concurrent Software - Java language
PPT
04 threads
PPT
Thread
PPTX
Thread & concurrancy
PPTX
THREADALLABOUTCOMOUTERHOWTOYHISDOTH.pptx
PPTX
Java Concurrency and Asynchronous
DOCX
Java 5 concurrency
PDF
Monitors and Blocking Synchronization : The Art of Multiprocessor Programming...
PPT
Slot03 concurrency2
PPTX
unit-3java.pptx
ODP
Java Concurrency, Memory Model, and Trends
PPT
Programming - Java-Threads-and-Synchronization.ppt
PPTX
PDF
CS844 U1 Individual Project
PDF
Java Multithreading Interview Questions PDF By ScholarHat
ODP
Java Concurrency
22 multi threading iv
Thread syncronization
Concurrency Learning From Jdk Source
Concurrency
Reliable and Concurrent Software - Java language
04 threads
Thread
Thread & concurrancy
THREADALLABOUTCOMOUTERHOWTOYHISDOTH.pptx
Java Concurrency and Asynchronous
Java 5 concurrency
Monitors and Blocking Synchronization : The Art of Multiprocessor Programming...
Slot03 concurrency2
unit-3java.pptx
Java Concurrency, Memory Model, and Trends
Programming - Java-Threads-and-Synchronization.ppt
CS844 U1 Individual Project
Java Multithreading Interview Questions PDF By ScholarHat
Java Concurrency

Recently uploaded (20)

PPTX
web development for engineering and engineering
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPT
Mechanical Engineering MATERIALS Selection
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Geodesy 1.pptx...............................................
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
Lecture Notes Electrical Wiring System Components
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
composite construction of structures.pdf
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PDF
PPT on Performance Review to get promotions
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
web development for engineering and engineering
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Mechanical Engineering MATERIALS Selection
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Geodesy 1.pptx...............................................
Automation-in-Manufacturing-Chapter-Introduction.pdf
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Lecture Notes Electrical Wiring System Components
R24 SURVEYING LAB MANUAL for civil enggi
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Operating System & Kernel Study Guide-1 - converted.pdf
UNIT-1 - COAL BASED THERMAL POWER PLANTS
composite construction of structures.pdf
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPT on Performance Review to get promotions
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd

[Java concurrency]02.basic thread synchronization

  • 1. Java Concurrency Basic Thread Synchronization zxholy@gmail.com
  • 2. In this chapter, we will cover: ● Synchronizing a method ● Arranging independent attributes in synchronized classes ● Using conditions in synchronized code ● Synchronizing a block of code with a Lock ● Synchronizing data access with read/write locks ● Modifying Lock fairness ● Using multiple conditions in a Lock
  • 3. Introduction ● Critical section A critical section is a block of code that accesses a shared resource and can't be executed by more than one thread at the same time.
  • 4. Introduction ● Synchronization mechanisms When a thread wants access to a critical section, it uses one of those synchronization mechanisms to find out if there is any other thread executing the critical section. If not, the thread enters the critical section. Otherwise, the thread is suspended by the synchronization mechanism until the thread that is executing the critical section ends it. When more than one thread is waiting for a thread to finish the execution of a critical section, the JVM chooses one of them, and the rest wait for their turn.
  • 5. Introduction Two basic synchronization mechanisms: ● The keyword synchronized ● The Lock interface and its implementations
  • 6. Synchronizing a method Every method declared with the synchronized keyword is a critical section and Java only allows the execution of one of the critical sections of an object. Static methods have a different behavior. Two threads can access two different synchronized methods if one is static and the other one is not.
  • 7. We will have a bank account and two threads; one that transfers money to the account and another one that withdraws money from the account. Synchronization mechanisms ensures that the final balance of the account will be correct.
  • 8. How to do it… Create a class called: Account One attribute: private double amount; Two method: addAmount() substractAmount();
  • 9. Two class: Bank and Company
  • 11. How it works... When remove synchronized keyword.
  • 12. The order of execution of the threads is not guaranteed by the JVM. Using the synchronized keyword, we guarantee correct access to shared data in concurrent applications.
  • 13. There is more... The synchronized keyword penalizes the performance of the application, so you must only use it on methods that modify shared data in a concurrent environment. You can use recursive calls with synchronized methods.
  • 14. We can use the synchronized keyword to protect the access to a block of code instead of an entire method.
  • 15. Arranging independent attributes in synchronized classes When executing the synchronized method which you use the this keyword as a parameter, you can only use other object references. But, now... ● Two independent attributes, synchronize the access to each variable. ● One thread accessing one attribute, another thread accessing another one.
  • 16. Simulates a cinema with two screens and two ticket offices. When a ticket office sells tickets, they are for one of the two cinemas, but not for both. So the numbers of free seats in each cinema are independent attributes.
  • 17. How to do it... Cinema class:
  • 21. How it works... When you use an object as a parameter of synchronized method, JVM guarantees that: Only one thread can have access to all the blocks of code protected with that object. Note: objects, not classes.
  • 22. We have two objects that controls access to the vacanciesCinema1 attribute and vacanciesCinema2 attribute separately. One thread can modify one attribute each time.
  • 23. Using conditions in synchronized code Producer-consumer problem: A classic problem in concurrent programming. ● A data buffer ○ A shared data structure ● One or more producers ○ Can’t save data in the buffer if it’s full ● One or more consumers ○ Can’t take data from the buffer if it’s empty
  • 24. Java provides the wait(), notify() and notifyAll() method s implemented in the Object class.
  • 25. wait() method Called by a thread, inside a synchronized block of code (Outside, JVM throws an IllegalMonitorStateException exception). The JVM puts the thread to sleep and releases the resources.
  • 26. To wake up the thread, you must call the notify() or notifyAll() method inside a block of code protected by the same object.
  • 27. Implement the producer-consumer problem using the synchronized keyword and the wait(), notify(), and notifyAll() methods.
  • 28. How to do it... EventStorage class:
  • 35. Synchronizing a block of code with a Lock Another mechanism for the synchronization of blocks of code. Based on Lock interface and classes that implement it (as ReentrantLock).
  • 36. Compare Lock and synchronized ● The mechanism based on Lock interface is more flexible. ● The Lock interfaces provide additional functionalities, as tryLock(). ● Allow a separation of read and write operations having multiple readers and only one modifier. ● Better performance
  • 37. Using the Lock interface and the ReentrantLock class that implements it, implementing a program that simulates a print queue.
  • 38. How to do it...
  • 42. There’s more... tryLock() method returns a boolean value, true if the thread gets the control of the lock, and false if not.
  • 43. The ReentrantLock class also allows the use of recursive calls. Avoid deadlocks. Situation: Two or more threads are blocked waiting for locks that never will be unlocked. Reason: Both threads try to get the locks in the opposite order.
  • 44. Modifying Lock fairness The constructor of the ReentrantLock and ReentrantReadWriteLock classes admits a boolean parameter named fair: false: non-fair mode selects one without any criteria. true: fair mode
  • 45. How to do it... Job class
  • 51. Synchronizing data access with read/write locks One of the most significant improvements offered by locks is the ReadWriteLock interface and the ReentrantReadWriteLock class, the unique one that implements it. Two locks: read/write
  • 52. Use ReadWriteLock to control the access to an object that stores the prices of two products.
  • 53. How to do it... PricesInfo class:
  • 59. Ensure the correct use of these locks, using them with the same purposes. When you get the read lock of a Lock interface, you can’t modify the calue of the variable.
  • 60. Using multiple conditions in a Lock A lock may be associated with one or more conditions. These conditions are declared in the Condition interface. The Condition interface provides the mechanisms to suspend a thread and to wake up a suspended thread.
  • 61. Condition ● Synchronized + monitor methods(wait, notify and notifyAll) ● Lock + Condition To obtain a Condition instance for a particular Lock instance use its newCondition() method.
  • 62. Producer-consumer problem. We have a data buffer, one or more producers of data that save it in the buffer, and one or more consumers of data that take it from the buffer as explained earlier in this chapter
  • 63. How to do it...
  • 72. How it works... When a thread calls the await() method of a condition, it automatically frees the control of the lock, so that another thread can get it and begin the execution of the same, or another critical section protected by that lock.
  • 73. You must be careful with the use of await() and signal(). You can use conditions with the ReadLock and WriteLock locks of a read/write lock.