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!
Ad

More Related Content

What's hot (20)

Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Java threading
Java threadingJava threading
Java threading
Chinh Ngo Nguyen
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
Appsterdam Milan
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Arafat Hossan
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
Alina Dolgikh
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
M. Raihan
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
myrajendra
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
kshanth2101
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
caswenson
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
Muthukumaran Subramanian
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
ducquoc_vn
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
Gaurav Aggarwal
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
AmbigaMurugesan
 
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 JAva
suraj pandey
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
Sunil OS
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
SivaRamaSundar Devasubramaniam
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Arafat Hossan
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
Alina Dolgikh
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
M. Raihan
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
myrajendra
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
kshanth2101
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
caswenson
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
ducquoc_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 JAva
suraj pandey
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
Sunil OS
 

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
Russel 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
 
如何更好地设计测试用例-BQConf
如何更好地设计测试用例-BQConf如何更好地设计测试用例-BQConf
如何更好地设计测试用例-BQConf
诸葛修车网-诸葛商城
 
大型网站架构演变
大型网站架构演变大型网站架构演变
大型网站架构演变
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 JVM
Pierre Laporte
 
Recipe 黃佳伶 葉愛慧
Recipe 黃佳伶 葉愛慧Recipe 黃佳伶 葉愛慧
Recipe 黃佳伶 葉愛慧
10y2try
 
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
Leon Chen
 
Lock Interface in Java
Lock Interface in JavaLock Interface in Java
Lock Interface in Java
Home
 
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
Misha 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 Collection
Haribabu Nandyal Padmanaban
 
Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best Practices
IndicThreads
 
JVM及其调优
JVM及其调优JVM及其调优
JVM及其调优
zhongbing liu
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
maksym220889
 
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
Russel 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 JVM
Pierre 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 OOM
Leon Chen
 
Lock Interface in Java
Lock Interface in JavaLock Interface in Java
Lock Interface in Java
Home
 
浅谈项目管理(诸葛B2B电商研发部版改)
浅谈项目管理(诸葛B2B电商研发部版改)浅谈项目管理(诸葛B2B电商研发部版改)
浅谈项目管理(诸葛B2B电商研发部版改)
诸葛修车网-诸葛商城
 
Implementing STM in Java
Implementing STM in JavaImplementing STM in Java
Implementing STM in Java
Misha 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 Collection
Haribabu Nandyal Padmanaban
 
Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best Practices
IndicThreads
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
maksym220889
 
Ad

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

Concurrency
ConcurrencyConcurrency
Concurrency
Sandeep Chawla
 
Concurrency
ConcurrencyConcurrency
Concurrency
Ankur Maheshwari
 
Programming - Java-Threads-and-Synchronization.ppt
Programming - Java-Threads-and-Synchronization.pptProgramming - Java-Threads-and-Synchronization.ppt
Programming - Java-Threads-and-Synchronization.ppt
smychung
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 
Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter Kit
Mark Papis
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
JanmejayaPadhiary2
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
G C Reddy Technologies
 
Threads and synchronization in C# visual programming.pptx
Threads and synchronization in C# visual programming.pptxThreads and synchronization in C# visual programming.pptx
Threads and synchronization in C# visual programming.pptx
azkamurat
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
Rakesh Jha
 
Concurrent/ parallel programming
Concurrent/ parallel programmingConcurrent/ parallel programming
Concurrent/ parallel programming
Tausun 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 questions
Gradeup
 
Multi threading
Multi threadingMulti threading
Multi threading
gndu
 
Java interview faq's
Java interview faq'sJava interview faq's
Java interview faq's
Deepak Raj
 
Java Advance Concepts
Java Advance ConceptsJava Advance Concepts
Java Advance Concepts
Emprovise
 
The Java Memory Model
The Java Memory ModelThe Java Memory Model
The Java Memory Model
CA Technologies
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Young Alista
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Tony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Hoang Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Harry Potter
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Fraboni Ec
 
Programming - Java-Threads-and-Synchronization.ppt
Programming - Java-Threads-and-Synchronization.pptProgramming - Java-Threads-and-Synchronization.ppt
Programming - Java-Threads-and-Synchronization.ppt
smychung
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 
Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter Kit
Mark Papis
 
Threads and synchronization in C# visual programming.pptx
Threads and synchronization in C# visual programming.pptxThreads and synchronization in C# visual programming.pptx
Threads and synchronization in C# visual programming.pptx
azkamurat
 
Multithreading and concurrency in android
Multithreading and concurrency in androidMultithreading and concurrency in android
Multithreading and concurrency in android
Rakesh Jha
 
Concurrent/ parallel programming
Concurrent/ parallel programmingConcurrent/ parallel programming
Concurrent/ parallel programming
Tausun 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 questions
Gradeup
 
Multi threading
Multi threadingMulti threading
Multi threading
gndu
 
Java interview faq's
Java interview faq'sJava interview faq's
Java interview faq's
Deepak Raj
 
Java Advance Concepts
Java Advance ConceptsJava Advance Concepts
Java Advance Concepts
Emprovise
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Young Alista
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Tony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Hoang Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Harry Potter
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
Fraboni Ec
 
Ad

Recently uploaded (20)

Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 

[Java concurrency]02.basic thread synchronization

  • 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.