SlideShare a Scribd company logo
THREAD SYNCRONIZATION IN JAVA
Threads
 Threads are lightweight processes as the overhead
of switching between threads is less
 The can be easily spawned
 The Java Virtual Machine spawns a thread when
your program is run called the Main Thread
Why do we need
threads?
 To enhance parallel processing
 To increase response to the user
 To utilize the idle time of the CPU
 Prioritize your work depending on priority
Example
• Consider a simple web server
• The web server listens for request and serves it
• If the web server was not multithreaded, the requests
processing would be in a queue, thus increasing the
response time and also might hang the server if there
was a bad request.
• By implementing in a multithreaded environment, the
web server can serve multiple request simultaneously
thus improving response time
Creating
threads
 In java threads can be created by
extending the Thread class or
implementing the Runnable Interface
 It is more preferred to implement the
Runnable Interface so that we can extend
properties from other classes
 Implement the run() method which is the
starting point for thread execution
Running threads
• Example
class mythread implements Runnable{
public void run(){
System.out.println(“Thread Started”);
}
}
class mainclass {
public static void main(String args[]){
Thread t = new Thread(new mythread()); // This is the way to
instantiate a thread implementing runnable
interface
t.start(); // starts the thread by running the run method
}
}
• Calling t.run() does not start a thread, it is just a
simple method call.
• Creating an object does not create a thread, calling
start() method creates the thread.
Synchronization
Synchronization is prevent
data corruption
Synchronization allows
only one thread to perform
an operation on a object at
a time.
If multiple threads require
an access to an object,
synchronization helps in
maintaining consistency.
Example
public class Counter{
private int count = 0;
public int getCount(){
return count;
}
public setCount(int count){
this.count = count;
}
}
 In this example, the counter tells how many an access
has been made.
 If a thread is accessing setCount and updating count
and another thread is accessing getCount at the same
time, there will be inconsistency in the value of count.
Fixing the example
public class Counter{
private static int count = 0;
public synchronized int getCount(){
return count;
}
public synchoronized setCount(int count){
this.count = count;
}
}
 By adding the synchronized keyword we make sure that
when one thread is in the setCount method the other
threads are all in waiting state.
 The synchronized keyword places a lock on the object,
and hence locks all the other methods which have the
keyword synchronized. The lock does not lock the
methods without the keyword synchronized and hence
they are open to access by other threads.
What about static
methods?
public class Counter{
private int count = 0;
public static synchronized int getCount(){
return count;
}
public static synchronized setCount(int count){
this.count = count;
}
}
 In this example the methods are static and hence are
associated with the class object and not the instance.
 Hence the lock is placed on the class object that is,
Counter.class object and not on the object itself. Any other non
static synchronized methods are still available for access by
other threads.
Common
Synchronization mistake
public class Counter{
private int count = 0;
public static synchronized int getCount(){
return count;
}
public synchronized setCount(int count){
this.count = count;
}
}
 The common mistake here is one method is static
synchronized and another method is non static synchronized.
 This makes a difference as locks are placed on two different
objects. The class object and the instance and hence two
different threads can access the methods simultaneously.
Object locking
• The object can be explicitly locked in this way
synchronized(myInstance){
try{
wait();
}catch(InterruptedException ex){
}
System.out.println(“Iam in this “);
notifyAll();
}
• The synchronized keyword locks the object. The wait keyword waits for
the lock to be acquired, if the object was already locked by another
thread. Notifyall() notifies other threads that the lock is about to be
released by the current thread.
• Another method notify() is available for use, which wakes up only the next
thread which is in queue for the object, notifyall() wakes up all the threads
and transfers the lock to another thread having the highest priority.
13
Thread Synchronization
• Monitors
• Object with synchronized methods
• Any object can be a monitor
• Methods declared synchronized
• public synchronized int myMethod( int x
)
• Only one thread can execute a synchronized
method at a time
• Obtaining the lock and locking an object
• If multiple synchronized methods, only one may be
active
• Java also has synchronized blocks of code
14
Thread Synchronization
• Thread may decide it cannot proceed
• May voluntarily call wait while accessing a
synchronized method
• Removes thread from contention for monitor object and
processor
• Thread in waiting state
• Other threads try to enter monitor object
• Suppose condition first thread needs has now been met
• Can call notify to tell a single waiting thread to enter
ready state
• notifyAll - tells all waiting threads to enter ready
state
15
Daemon Threads
• Daemon threads
• Threads that run for benefit of other
threads
• E.g., garbage collector
• Run in background
• Use processor time that would
otherwise go to waste
• Unlike normal threads, do not
prevent a program from terminating -
when only daemon threads remain,
program exits
• Must designate a thread as daemon
before start called:
void setDaemon( true );
• Method boolean isDaemon()
• Returns true if thread is a daemon
thread
SchedulingThreads
I/O operation completes
start()
Currently executed
thread
Ready queue
•Waiting for I/O operation to be completed
•Waiting to be notified
•Sleeping
•Waiting to enter a synchronized section
Newly created
threads
What happens when
a program with a
ServerSocket calls
accept()?
Critical
Section
 The synchronized methods define
critical sections
 Execution of critical sections is mutually
exclusive. Why?
Example
public class BankAccount {
private float balance;
public synchronized void deposit(float amount) {
balance += amount;
}
public synchronized void withdraw(float amount) {
balance -= amount;
}
}
Critical Sections
Bank Account
deposit()
t1t2t3
Deadlock Example
public class BankAccount {
private float balance;
public synchronized void deposit(float amount) {
balance += amount;
}
public synchronized void withdraw(float amount) {
balance -= amount;
}
public synchronized void transfer(float amount,
BankAccount target) {
withdraw(amount);
target.deposit(amount);
}
}
public class MoneyTransfer implements Runnable {
private BankAccount from, to;
private float amount;
public MoneyTransfer(
BankAccount from, BankAccount to, float amount) {
this.from = from;
this.to = to;
this.amount = amount;
}
public void run() {
source.transfer(amount, target);
}
}
BankAccount aliceAccount = new BankAccount();
BankAccount bobAccount = new BankAccount();
...
// At one place
Runnable transaction1 =
new MoneyTransfer(aliceAccount, bobAccount, 1200);
Thread t1 = new Thread(transaction1);
t1.start();
// At another place
Runnable transaction2 =
new MoneyTransfer(bobAccount, aliceAccount, 700);
Thread t2 = new Thread(transaction2);
t2.start();
Deadlocks
deposit()
aliceAccount bobAccount
t1 t2
deposit()
?
transfer()
withdraw()
transfer()
withdraw()
Thread Synchronization
 We need to synchronized between
transactions, for example, the consumer-
producer scenario
Wait and Notify
 Allows two threads to cooperate
 Based on a single shared lock object
 Marge put a cookie wait and notify Homer
 Homer eat a cookie wait and notify Marge
 Marge put a cookie wait and notify Homer
 Homer eat a cookie wait and notify Marge
The wait() Method
 The wait() method is part of the
java.lang.Object interface
 It requires a lock on the object’s monitor to execute
 It must be called from a synchronized method, or from a
synchronized segment of code. Why?
Consumer
synchronized (lock) {
while (!resourceAvailable()) {
lock.wait();
}
consumeResource();
}
Producer
produceResource();
synchronized (lock) {
lock.notifyAll();
}
WAIT/NOTIFY SEQUENCE
Lock Object
Consumer
Thread
Producer
Thread
1. synchronized(lock){
2. lock.wait();
3. produceResource()
4. synchronized(lock) {
5. lock.notify();
6.}
7. Reacquire lock
8. Return from wait()
9. consumeResource();
10. }
WAIT/NOTIFY SEQUENCE
Lock Object
Consumer
Thread
Producer
Thread
1. synchronized(lock){
2. lock.wait();
3. produceResource()
4. synchronized(lock) {
5. lock.notify();
6.}
7. Reacquire lock
8. Return from wait()
9. consumeResource();
10. }
WAIT/NOTIFY SEQUENCE
Lock Object
Consumer
Thread
Producer
Thread
1. synchronized(lock){
2. lock.wait();
3. produceResource()
4. synchronized(lock) {
5. lock.notify();
6.}
7. Reacquire lock
8. Return from wait()
9. consumeResource();
10. }
WAIT/NOTIFY SEQUENCE
Lock Object
Consumer
Thread
Producer
Thread
1. synchronized(lock){
2. lock.wait();
3. produceResource()
4. synchronized(lock) {
5. lock.notify();
6.}
7. Reacquire lock
8. Return from wait()
9. consumeResource();
10. }
WAIT/NOTIFY SEQUENCE
Lock Object
Consumer
Thread
Producer
Thread
1. synchronized(lock){
2. lock.wait();
3. produceResource()
4. synchronized(lock) {
5. lock.notify();
6.}
7. Reacquire lock
8. Return from wait()
9. consumeResource();
10. }
WAIT/NOTIFY SEQUENCE
Lock Object
Consumer
Thread
Producer
Thread
1. synchronized(lock){
2. lock.wait();
3. produceResource()
4. synchronized(lock) {
5. lock.notify();
6.}
7. Reacquire lock
8. Return from wait()
9. consumeResource();
10. }
WAIT/NOTIFY SEQUENCE
Lock Object
Consumer
Thread
Producer
Thread
1. synchronized(lock){
2. lock.wait();
3. produceResource()
4. synchronized(lock) {
5. lock.notify();
6.}
7. Reacquire lock
8. Return from wait()
9. consumeResource();
10. }
WAIT/NOTIFY SEQUENCE
Lock Object
Consumer
Thread
Producer
Thread
1. synchronized(lock){
2. lock.wait();
3. produceResource()
4. synchronized(lock) {
5. lock.notify();
6.}
7. Reacquire lock
8. Return from wait()
9. consumeResource();
10. }
WAIT/NOTIFY SEQUENCE
Lock Object
Consumer
Thread
Producer
Thread
1. synchronized(lock){
2. lock.wait();
3. produceResource()
4. synchronized(lock) {
5. lock.notify();
6.}
7. Reacquire lock
8. Return from wait()
9. consumeResource();
10. }
WAIT/NOTIFY SEQUENCE
Lock Object
Consumer
Thread
Producer
Thread
1. synchronized(lock){
2. lock.wait();
3. produceResource()
4. synchronized(lock) {
5. lock.notify();
6.}
7. Reacquire lock
8. Return from wait()
9. consumeResource();
10. }
WAIT/NOTIFY SEQUENCE
Lock Object
Consumer
Thread
Producer
Thread
1. synchronized(lock){
2. lock.wait();
3. produceResource()
4. synchronized(lock) {
5. lock.notify();
6.}
7. Reacquire lock
8. Return from wait()
9. consumeResource();
10. }

More Related Content

What's hot

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
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
ducquoc_vn
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
kshanth2101
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
xuehan zhu
 
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
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
xuehan zhu
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Sachintha Gunasena
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
Allan Huang
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
Appsterdam Milan
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningCarol McDonald
 
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Sachintha Gunasena
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
Alex Miller
 
Thread 1
Thread 1Thread 1
Thread 1
RAVI MAURYA
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
Medhat Dawoud
 
Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#
Rizwan Ali
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
Neera Mital
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreading
Tuan Chau
 

What's hot (20)

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...
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
 
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)
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
Thread 1
Thread 1Thread 1
Thread 1
 
Threading in C#
Threading in C#Threading in C#
Threading in C#
 
Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreading
 

Similar to Thread syncronization

Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
Neeraj Kaushik
 
Java Thread
Java ThreadJava Thread
Java Thread
DeeptiJava
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
PreetiDixit22
 
chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)
It Academy
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
Sasha Kravchuk
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
raksharao
 
Multithreading
MultithreadingMultithreading
Multithreadingbackdoor
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontrackingvamsi krishna
 
Multithreading
MultithreadingMultithreading
Multithreadingsagsharma
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
ssusere538f7
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
Vikram Kalyani
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
multithreading
multithreadingmultithreading
multithreading
Rajkattamuri
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 

Similar to Thread syncronization (20)

Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Java Thread
Java ThreadJava Thread
Java Thread
 
22 multi threading iv
22 multi threading iv22 multi threading iv
22 multi threading iv
 
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
Java adv
Java advJava adv
Java adv
 
chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Chap3 multi threaded programming
Chap3 multi threaded programmingChap3 multi threaded programming
Chap3 multi threaded programming
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
Lecture10
Lecture10Lecture10
Lecture10
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Thread
ThreadThread
Thread
 
multithreading
multithreadingmultithreading
multithreading
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 

Recently uploaded

Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
AhmedHussein950959
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
ViniHema
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 

Recently uploaded (20)

Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
power quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptxpower quality voltage fluctuation UNIT - I.pptx
power quality voltage fluctuation UNIT - I.pptx
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 

Thread syncronization

  • 2. Threads  Threads are lightweight processes as the overhead of switching between threads is less  The can be easily spawned  The Java Virtual Machine spawns a thread when your program is run called the Main Thread
  • 3. Why do we need threads?  To enhance parallel processing  To increase response to the user  To utilize the idle time of the CPU  Prioritize your work depending on priority
  • 4. Example • Consider a simple web server • The web server listens for request and serves it • If the web server was not multithreaded, the requests processing would be in a queue, thus increasing the response time and also might hang the server if there was a bad request. • By implementing in a multithreaded environment, the web server can serve multiple request simultaneously thus improving response time
  • 5. Creating threads  In java threads can be created by extending the Thread class or implementing the Runnable Interface  It is more preferred to implement the Runnable Interface so that we can extend properties from other classes  Implement the run() method which is the starting point for thread execution
  • 6. Running threads • Example class mythread implements Runnable{ public void run(){ System.out.println(“Thread Started”); } } class mainclass { public static void main(String args[]){ Thread t = new Thread(new mythread()); // This is the way to instantiate a thread implementing runnable interface t.start(); // starts the thread by running the run method } } • Calling t.run() does not start a thread, it is just a simple method call. • Creating an object does not create a thread, calling start() method creates the thread.
  • 7. Synchronization Synchronization is prevent data corruption Synchronization allows only one thread to perform an operation on a object at a time. If multiple threads require an access to an object, synchronization helps in maintaining consistency.
  • 8. Example public class Counter{ private int count = 0; public int getCount(){ return count; } public setCount(int count){ this.count = count; } }  In this example, the counter tells how many an access has been made.  If a thread is accessing setCount and updating count and another thread is accessing getCount at the same time, there will be inconsistency in the value of count.
  • 9. Fixing the example public class Counter{ private static int count = 0; public synchronized int getCount(){ return count; } public synchoronized setCount(int count){ this.count = count; } }  By adding the synchronized keyword we make sure that when one thread is in the setCount method the other threads are all in waiting state.  The synchronized keyword places a lock on the object, and hence locks all the other methods which have the keyword synchronized. The lock does not lock the methods without the keyword synchronized and hence they are open to access by other threads.
  • 10. What about static methods? public class Counter{ private int count = 0; public static synchronized int getCount(){ return count; } public static synchronized setCount(int count){ this.count = count; } }  In this example the methods are static and hence are associated with the class object and not the instance.  Hence the lock is placed on the class object that is, Counter.class object and not on the object itself. Any other non static synchronized methods are still available for access by other threads.
  • 11. Common Synchronization mistake public class Counter{ private int count = 0; public static synchronized int getCount(){ return count; } public synchronized setCount(int count){ this.count = count; } }  The common mistake here is one method is static synchronized and another method is non static synchronized.  This makes a difference as locks are placed on two different objects. The class object and the instance and hence two different threads can access the methods simultaneously.
  • 12. Object locking • The object can be explicitly locked in this way synchronized(myInstance){ try{ wait(); }catch(InterruptedException ex){ } System.out.println(“Iam in this “); notifyAll(); } • The synchronized keyword locks the object. The wait keyword waits for the lock to be acquired, if the object was already locked by another thread. Notifyall() notifies other threads that the lock is about to be released by the current thread. • Another method notify() is available for use, which wakes up only the next thread which is in queue for the object, notifyall() wakes up all the threads and transfers the lock to another thread having the highest priority.
  • 13. 13 Thread Synchronization • Monitors • Object with synchronized methods • Any object can be a monitor • Methods declared synchronized • public synchronized int myMethod( int x ) • Only one thread can execute a synchronized method at a time • Obtaining the lock and locking an object • If multiple synchronized methods, only one may be active • Java also has synchronized blocks of code
  • 14. 14 Thread Synchronization • Thread may decide it cannot proceed • May voluntarily call wait while accessing a synchronized method • Removes thread from contention for monitor object and processor • Thread in waiting state • Other threads try to enter monitor object • Suppose condition first thread needs has now been met • Can call notify to tell a single waiting thread to enter ready state • notifyAll - tells all waiting threads to enter ready state
  • 15. 15 Daemon Threads • Daemon threads • Threads that run for benefit of other threads • E.g., garbage collector • Run in background • Use processor time that would otherwise go to waste • Unlike normal threads, do not prevent a program from terminating - when only daemon threads remain, program exits • Must designate a thread as daemon before start called: void setDaemon( true ); • Method boolean isDaemon() • Returns true if thread is a daemon thread
  • 16. SchedulingThreads I/O operation completes start() Currently executed thread Ready queue •Waiting for I/O operation to be completed •Waiting to be notified •Sleeping •Waiting to enter a synchronized section Newly created threads What happens when a program with a ServerSocket calls accept()?
  • 17. Critical Section  The synchronized methods define critical sections  Execution of critical sections is mutually exclusive. Why?
  • 18. Example public class BankAccount { private float balance; public synchronized void deposit(float amount) { balance += amount; } public synchronized void withdraw(float amount) { balance -= amount; } }
  • 20. Deadlock Example public class BankAccount { private float balance; public synchronized void deposit(float amount) { balance += amount; } public synchronized void withdraw(float amount) { balance -= amount; } public synchronized void transfer(float amount, BankAccount target) { withdraw(amount); target.deposit(amount); } }
  • 21. public class MoneyTransfer implements Runnable { private BankAccount from, to; private float amount; public MoneyTransfer( BankAccount from, BankAccount to, float amount) { this.from = from; this.to = to; this.amount = amount; } public void run() { source.transfer(amount, target); } }
  • 22. BankAccount aliceAccount = new BankAccount(); BankAccount bobAccount = new BankAccount(); ... // At one place Runnable transaction1 = new MoneyTransfer(aliceAccount, bobAccount, 1200); Thread t1 = new Thread(transaction1); t1.start(); // At another place Runnable transaction2 = new MoneyTransfer(bobAccount, aliceAccount, 700); Thread t2 = new Thread(transaction2); t2.start();
  • 24. Thread Synchronization  We need to synchronized between transactions, for example, the consumer- producer scenario
  • 25. Wait and Notify  Allows two threads to cooperate  Based on a single shared lock object  Marge put a cookie wait and notify Homer  Homer eat a cookie wait and notify Marge  Marge put a cookie wait and notify Homer  Homer eat a cookie wait and notify Marge
  • 26. The wait() Method  The wait() method is part of the java.lang.Object interface  It requires a lock on the object’s monitor to execute  It must be called from a synchronized method, or from a synchronized segment of code. Why?
  • 27. Consumer synchronized (lock) { while (!resourceAvailable()) { lock.wait(); } consumeResource(); }
  • 29. WAIT/NOTIFY SEQUENCE Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }
  • 30. WAIT/NOTIFY SEQUENCE Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }
  • 31. WAIT/NOTIFY SEQUENCE Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }
  • 32. WAIT/NOTIFY SEQUENCE Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }
  • 33. WAIT/NOTIFY SEQUENCE Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }
  • 34. WAIT/NOTIFY SEQUENCE Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }
  • 35. WAIT/NOTIFY SEQUENCE Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }
  • 36. WAIT/NOTIFY SEQUENCE Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }
  • 37. WAIT/NOTIFY SEQUENCE Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }
  • 38. WAIT/NOTIFY SEQUENCE Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }
  • 39. WAIT/NOTIFY SEQUENCE Lock Object Consumer Thread Producer Thread 1. synchronized(lock){ 2. lock.wait(); 3. produceResource() 4. synchronized(lock) { 5. lock.notify(); 6.} 7. Reacquire lock 8. Return from wait() 9. consumeResource(); 10. }