SlideShare une entreprise Scribd logo
1  sur  14
Télécharger pour lire hors ligne
Synchronization
• When two or more threads need access to a shared
resource, they need some way to ensure that the resource
will be used by only one thread at a time. The process by
which this is achieved is called synchronization.
• Java provides unique, language-level support for it. Key to
synchronization is the concept of the monitor (also called a
semaphore).
• A monitor is an object that is used as a mutually exclusive
lock, or mutex. Only one thread can own a monitor at a
given time. When a thread acquires a lock, it is said to have
entered the monitor. All other threads attempting to enter
the locked monitor will be suspended until the first thread
exits the monitor. These other threads are said to be
waiting for the monitor. A thread that owns a monitor can
reenter the same monitor if it so desires.
• We can synchronize our code in either of two ways. Both
involve the use of the synchronized keyword, and both are
examined here.
• Using synchronized Methods
• The synchronized Statement
• synchronized Methods : All objects have their own implicit
monitor associated with them. To enter an object’s monitor,
just call a method that has been modified with the
synchronized keyword. While a thread is inside a synchronized
method, all other threads that try to call it (or any other
synchronized method) on the same instance have to wait. To
exit the monitor and relinquish control of the object to the
next waiting thread, the owner of the monitor simply returns
from the synchronized method.
class callme{
static int i=1;
//synchronized
static void print() {
System.out.print("( HI ");
try { Thread.sleep(1000);
}
catch(InterruptedException e) { System.out.println("Interrupted");
}
System.out.println(i+" )");
i++;
} }
class A extends Thread {
public void run() {
for(int i=1;i<=5;i++)
callme.print();
} }
class B extends Thread{
public void run() {
for(int i=1;i<=5;i++)
callme.print();
}
}
class test {
public static void main(String args[])
{
A th1= new A();
th1.start(); // new A().start();
B th2=new B();
th2.start();
}
}
( HI ( HI 1 )
1 )
( HI ( HI 3 )
( HI 3 )
( HI 5 )
( HI 5 )
( HI 7 )
( HI 7 )
( HI 9 )
9 )
• Here the value of variable i is updated in unordered way by both
the threads A and B. The output may change for each run. This can
lead to a series problem if i is some important shared data or a
control flag. The output printing is also not in order. To solve the
problem we need synchronization over the print() method.
• If the print() method is defined as:
synchronized static void print(){---------}
• Then the method is synchronized and the output will be->
( HI 1 )
( HI 2 )
( HI 3 )
( HI 4 )
( HI 5 )
( HI 6 )
( HI 7 )
( HI 8 )
( HI 9 )
( HI 10 )
• Also the output will remain same for each run.(As only one thread can
execute the print() method at a time and other thread has to wait for
completion of current call to print method.)
• The synchronized Statement: While creating synchronized methods
within classes that you create is an easy and effective means of achieving
synchronization, it will not work in all cases.
• Consider the following. Imagine that we want to synchronize access to
objects of a class that was not designed for multithreaded access. That is,
the class does not use synchronized methods. Further, this class was not
created by us, but by a third party, and we do not have access to the
source code. Thus, we can’t add synchronized to the appropriate methods
within the class. How can access to an object of this class be
synchronized?
• The solution to this problem is quite easy: simply put calls to the methods
defined by this class inside a synchronized block.
synchronized(object) {
// statements to be synchronized
}
• Here, object is a reference to the object being synchronized. A synchronized
block ensures that a call to a method that is a member of object occurs
only after the current thread has successfully entered object’s monitor.
class callme{
int i=1; //non-static member
void print() { //non-static member
System.out.print("( HI ");
try { Thread.sleep(1000); }
catch(InterruptedException e) { System.out.println("Interrupted"); }
System.out.println(i+" )");
i++;
} }
class A extends Thread {
callme obj;
A(callme target) { obj=target; }
public void run() {
for(int i=1;i<=5;i++) {
synchronized(obj)
{ obj.print(); } }
} }
class B extends Thread{
callme obj;
B(callme target){ obj=target; }
public void run() {
for(int i=1;i<=5;i++)
{ synchronized(obj)
{obj.print(); } }
} }
class test {
public static void main(String args[]) {
callme obj1=new callme();
A th1= new A(obj1);
th1.start(); // new A().start();
B th2=new B(obj1);
th2.start();
}
}
• Here both thread are referring to the same instance/object of class
callme. The call to method print() is in synchronized block this time.
( HI 1 )
( HI 2 )
( HI 3 )
( HI 4 )
……..
( HI 9 )
( HI 10 )
So here without changing the original class callme the call to print
method is executed in synchronized block. This will have the same
effect as the previous case.(Where the print method is ynchronized.)
Interthread Communication
• Polling is usually implemented by a loop that is used to
check some condition repeatedly. Once the condition is
true, appropriate action is taken. This wastes CPU time.
• To avoid polling, Java includes an elegant interprocess
communication mechanism via the wait( ), notify( ), and
notifyAll( ) methods. These methods are implemented as
final methods in Object, so all classes have them. All three
methods can be called only from within a synchronized
context.
• wait( ) tells the calling thread to give up the monitor and go
to sleep until some other thread enters the same monitor
and calls notify( ).
• notify( ) wakes up the first thread that called wait( ) on the
same object.
• notifyAll( ) wakes up all the threads that called wait( ) on
the same object. The highest priority thread will run first.
• These methods are declared within Object, as
shown here:
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
class A {
public static void main(String[]args)throws InterruptedException {
B b =new B();
b.start();
synchronized(b) //thread got lock
{
System.out.println("Calling wait method");
b.wait();
System.out.println("Got notification"); }
System.out.println(b.total);
} }
class B extends Thread{
int total=0;
public void run() {
synchronized (this) //.thread got lock
{
System.out.println("Starting calculation");
for(int i=0;i<=1000;i++) { total=total+I; }
System.out.println("Giving notification call");
notify(); //thread releases lock again }} }
Calling wait method
Starting calculation
Giving notification call
Got notification
500500

Contenu connexe

Tendances

Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-threadjavaicon
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded ApplicationsBharat17485
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threadingAPU
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs.NET: Thread Synchronization Constructs
.NET: Thread Synchronization ConstructsSasha Kravchuk
 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
 
Thread model of java
Thread model of javaThread model of java
Thread model of javamyrajendra
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaArafat Hossan
 

Tendances (20)

Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-thread
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharp
 
.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs
 
multi threading
multi threadingmulti threading
multi threading
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
 
javathreads
javathreadsjavathreads
javathreads
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Java thread
Java threadJava thread
Java thread
 

En vedette

En vedette (20)

26 io -ii file handling
26  io -ii  file handling26  io -ii  file handling
26 io -ii file handling
 
Ch11 communication
Ch11  communicationCh11  communication
Ch11 communication
 
Introduction of reflection
Introduction of reflection Introduction of reflection
Introduction of reflection
 
28 networking
28  networking28  networking
28 networking
 
21 multi threading - iii
21 multi threading - iii21 multi threading - iii
21 multi threading - iii
 
Lecture 5 phasor notations
Lecture 5 phasor notationsLecture 5 phasor notations
Lecture 5 phasor notations
 
Vlsi
VlsiVlsi
Vlsi
 
Fiber optics101
Fiber optics101Fiber optics101
Fiber optics101
 
Spread spectrum
Spread spectrumSpread spectrum
Spread spectrum
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
 
T com presentation (error correcting code)
T com presentation   (error correcting code)T com presentation   (error correcting code)
T com presentation (error correcting code)
 
Low noise amplifier csd
Low noise amplifier csdLow noise amplifier csd
Low noise amplifier csd
 
Digital Communication 2
Digital Communication 2Digital Communication 2
Digital Communication 2
 
Line coding
Line codingLine coding
Line coding
 
Digital Communication 4
Digital Communication 4Digital Communication 4
Digital Communication 4
 
Limits
LimitsLimits
Limits
 
Trigonometry101
Trigonometry101Trigonometry101
Trigonometry101
 
Analytic geometry lecture2
Analytic geometry lecture2Analytic geometry lecture2
Analytic geometry lecture2
 
Data Communication 1
Data Communication 1Data Communication 1
Data Communication 1
 
27 applet programming
27  applet programming27  applet programming
27 applet programming
 

Similaire à 22 multi threading iv

Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfacekeval_thummar
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptxnimbalkarvikram966
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading PresentationNeeraj Kaushik
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
Multithreading
MultithreadingMultithreading
Multithreadingbackdoor
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptxcreativegamerz00
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVAVikram Kalyani
 
More topics on Java
More topics on JavaMore topics on Java
More topics on JavaAhmed Misbah
 
Inter Thread Communicationn.pptx
Inter Thread Communicationn.pptxInter Thread Communicationn.pptx
Inter Thread Communicationn.pptxSelvakumarNSNS
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreadingTuan Chau
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptxssuserfcae42
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 

Similaire à 22 multi threading iv (20)

Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interface
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
 
Oops
OopsOops
Oops
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
More topics on Java
More topics on JavaMore topics on Java
More topics on Java
 
Inter Thread Communicationn.pptx
Inter Thread Communicationn.pptxInter Thread Communicationn.pptx
Inter Thread Communicationn.pptx
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreading
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
multithreading.pptx
multithreading.pptxmultithreading.pptx
multithreading.pptx
 
Java
JavaJava
Java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

Dernier

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 

Dernier (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

22 multi threading iv

  • 1. Synchronization • When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. • Java provides unique, language-level support for it. Key to synchronization is the concept of the monitor (also called a semaphore). • A monitor is an object that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor. These other threads are said to be waiting for the monitor. A thread that owns a monitor can reenter the same monitor if it so desires.
  • 2. • We can synchronize our code in either of two ways. Both involve the use of the synchronized keyword, and both are examined here. • Using synchronized Methods • The synchronized Statement • synchronized Methods : All objects have their own implicit monitor associated with them. To enter an object’s monitor, just call a method that has been modified with the synchronized keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on the same instance have to wait. To exit the monitor and relinquish control of the object to the next waiting thread, the owner of the monitor simply returns from the synchronized method.
  • 3. class callme{ static int i=1; //synchronized static void print() { System.out.print("( HI "); try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("Interrupted"); } System.out.println(i+" )"); i++; } } class A extends Thread { public void run() { for(int i=1;i<=5;i++) callme.print(); } }
  • 4. class B extends Thread{ public void run() { for(int i=1;i<=5;i++) callme.print(); } } class test { public static void main(String args[]) { A th1= new A(); th1.start(); // new A().start(); B th2=new B(); th2.start(); } }
  • 5. ( HI ( HI 1 ) 1 ) ( HI ( HI 3 ) ( HI 3 ) ( HI 5 ) ( HI 5 ) ( HI 7 ) ( HI 7 ) ( HI 9 ) 9 ) • Here the value of variable i is updated in unordered way by both the threads A and B. The output may change for each run. This can lead to a series problem if i is some important shared data or a control flag. The output printing is also not in order. To solve the problem we need synchronization over the print() method. • If the print() method is defined as: synchronized static void print(){---------}
  • 6. • Then the method is synchronized and the output will be-> ( HI 1 ) ( HI 2 ) ( HI 3 ) ( HI 4 ) ( HI 5 ) ( HI 6 ) ( HI 7 ) ( HI 8 ) ( HI 9 ) ( HI 10 ) • Also the output will remain same for each run.(As only one thread can execute the print() method at a time and other thread has to wait for completion of current call to print method.)
  • 7. • The synchronized Statement: While creating synchronized methods within classes that you create is an easy and effective means of achieving synchronization, it will not work in all cases. • Consider the following. Imagine that we want to synchronize access to objects of a class that was not designed for multithreaded access. That is, the class does not use synchronized methods. Further, this class was not created by us, but by a third party, and we do not have access to the source code. Thus, we can’t add synchronized to the appropriate methods within the class. How can access to an object of this class be synchronized? • The solution to this problem is quite easy: simply put calls to the methods defined by this class inside a synchronized block. synchronized(object) { // statements to be synchronized } • Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a method that is a member of object occurs only after the current thread has successfully entered object’s monitor.
  • 8. class callme{ int i=1; //non-static member void print() { //non-static member System.out.print("( HI "); try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("Interrupted"); } System.out.println(i+" )"); i++; } } class A extends Thread { callme obj; A(callme target) { obj=target; } public void run() { for(int i=1;i<=5;i++) { synchronized(obj) { obj.print(); } } } }
  • 9. class B extends Thread{ callme obj; B(callme target){ obj=target; } public void run() { for(int i=1;i<=5;i++) { synchronized(obj) {obj.print(); } } } } class test { public static void main(String args[]) { callme obj1=new callme(); A th1= new A(obj1); th1.start(); // new A().start(); B th2=new B(obj1); th2.start(); } }
  • 10. • Here both thread are referring to the same instance/object of class callme. The call to method print() is in synchronized block this time. ( HI 1 ) ( HI 2 ) ( HI 3 ) ( HI 4 ) …….. ( HI 9 ) ( HI 10 ) So here without changing the original class callme the call to print method is executed in synchronized block. This will have the same effect as the previous case.(Where the print method is ynchronized.)
  • 11. Interthread Communication • Polling is usually implemented by a loop that is used to check some condition repeatedly. Once the condition is true, appropriate action is taken. This wastes CPU time. • To avoid polling, Java includes an elegant interprocess communication mechanism via the wait( ), notify( ), and notifyAll( ) methods. These methods are implemented as final methods in Object, so all classes have them. All three methods can be called only from within a synchronized context. • wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ). • notify( ) wakes up the first thread that called wait( ) on the same object. • notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest priority thread will run first.
  • 12. • These methods are declared within Object, as shown here: final void wait( ) throws InterruptedException final void notify( ) final void notifyAll( )
  • 13. class A { public static void main(String[]args)throws InterruptedException { B b =new B(); b.start(); synchronized(b) //thread got lock { System.out.println("Calling wait method"); b.wait(); System.out.println("Got notification"); } System.out.println(b.total); } } class B extends Thread{ int total=0; public void run() { synchronized (this) //.thread got lock { System.out.println("Starting calculation"); for(int i=0;i<=1000;i++) { total=total+I; } System.out.println("Giving notification call"); notify(); //thread releases lock again }} }
  • 14. Calling wait method Starting calculation Giving notification call Got notification 500500