SlideShare a Scribd company logo
1 of 74
Download to read offline
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
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:
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...
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...
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
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...
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

What's hot

Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaArafat Hossan
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in JavaM. Raihan
 
Thread model of java
Thread model of javaThread model of java
Thread model of javamyrajendra
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyAnton Keks
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...Sachintha Gunasena
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAvasuraj pandey
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 

What's hot (20)

Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Java threading
Java threadingJava threading
Java threading
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
 

Viewers also liked

Closures: The Next "Big Thing" In Java
Closures: The Next "Big Thing" In JavaClosures: The Next "Big Thing" In Java
Closures: The Next "Big Thing" In JavaRussel Winder
 
Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)Kaunas Java User Group
 
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)
自己的JVM自己救: 解救 OOM 實務經驗談  (JCConf 2015)自己的JVM自己救: 解救 OOM 實務經驗談  (JCConf 2015)
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)Leon Chen
 
大型网站架构演变
大型网站架构演变大型网站架构演变
大型网站架构演变xiaozhen1900
 
Building a lock profiler on the JVM
Building a lock profiler on the JVMBuilding a lock profiler on the JVM
Building a lock profiler on the JVMPierre Laporte
 
Recipe 黃佳伶 葉愛慧
Recipe 黃佳伶 葉愛慧Recipe 黃佳伶 葉愛慧
Recipe 黃佳伶 葉愛慧10y2try
 
Save JVM by Yourself: Real War Experiences of OOM
Save JVM by Yourself: Real War Experiences of OOMSave JVM by Yourself: Real War Experiences of OOM
Save JVM by Yourself: Real War Experiences of OOMLeon Chen
 
Lock Interface in Java
Lock Interface in JavaLock Interface in Java
Lock Interface in JavaHome
 
浅谈项目管理(诸葛B2B电商研发部版改)
浅谈项目管理(诸葛B2B电商研发部版改)浅谈项目管理(诸葛B2B电商研发部版改)
浅谈项目管理(诸葛B2B电商研发部版改)诸葛修车网-诸葛商城
 
Implementing STM in Java
Implementing STM in JavaImplementing STM in Java
Implementing STM in JavaMisha Kozik
 
Thrift+scribe实现分布式日志收集,并与log4j集成
Thrift+scribe实现分布式日志收集,并与log4j集成Thrift+scribe实现分布式日志收集,并与log4j集成
Thrift+scribe实现分布式日志收集,并与log4j集成zhongbing liu
 
Performance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionPerformance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionHaribabu Nandyal Padmanaban
 
Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best PracticesIndicThreads
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread poolsmaksym220889
 

Viewers also liked (20)

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

Similar to [Java concurrency]02.basic thread synchronization

Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter KitMark Papis
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in androidRakesh Jha
 
Concurrent/ parallel programming
Concurrent/ parallel programmingConcurrent/ parallel programming
Concurrent/ parallel programmingTausun Akhtary
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questionsGradeup
 
Multi threading
Multi threadingMulti threading
Multi threadinggndu
 
Java interview faq's
Java interview faq'sJava interview faq's
Java interview faq'sDeepak Raj
 
Java Advance Concepts
Java Advance ConceptsJava Advance Concepts
Java Advance ConceptsEmprovise
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaLuis Goldster
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaHarry Potter
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaYoung Alista
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaTony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaFraboni Ec
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaHoang Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaJames Wong
 

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

Concurrency
ConcurrencyConcurrency
Concurrency
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter Kit
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
 
Concurrent/ parallel programming
Concurrent/ parallel programmingConcurrent/ parallel programming
Concurrent/ parallel programming
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Java interview faq's
Java interview faq'sJava interview faq's
Java interview faq's
 
Java Advance Concepts
Java Advance ConceptsJava Advance Concepts
Java Advance Concepts
 
The Java Memory Model
The Java Memory ModelThe Java Memory Model
The Java Memory Model
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 

Recently uploaded

VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 

Recently uploaded (20)

VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 

[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
  • 10.
  • 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:
  • 20.
  • 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:
  • 34.
  • 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...
  • 39.
  • 40.
  • 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
  • 46.
  • 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...
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 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.