SlideShare a Scribd company logo
1 of 12
Multithreading in Java – Part 3
Thread Safety
By,
Srinivas
JAVA9S.comJAVA9S.com
Need for Thread Safety
DataThread 1
Thread 2
Total Balance = 500
Withdraw amount
Wife = 450; Husband = 100
???
No Funds available
Java Application
JAVA9S.comJAVA9S.com
Need for Thread Safety
Happybus.com
Total Seats left: 3
No.of Seats wanted: 2 No.of Seats wanted: 2
When both of them get a chance to book at same time – then any one
of them will get a message that there are no sufficient seats left
JAVA9S.comJAVA9S.com
Code – Without Thread Safety
Demo
JAVA9S.comJAVA9S.com
Code Synchronization for thread
safety• Code Synchronization helps in preventing multiple threads
executing a code simultaneously.
• Code Synchronization is implemented with the help of Locks.
• A thread that is trying to access the code that is marked as
Synchronized should acquire the lock from the object.
• Locks:
– Every object has a lock. Only one lock per object.
– Every class has a lock. Only one lock per loaded class file. (For static
methods)
JAVA9S.comJAVA9S.com
Synchronize - Few points
• Synchronize can only be applied for methods and
block of code.
• Synchronize cannot be applied for classes and
instance fields.
Syntax:
public synchronize void method(){ }
public static synchronize void method{…}
synchronize(this){…}
JAVA9S.comJAVA9S.com
Locks for Thread Safety
M1 M2 M3
Methodss s
M1 M2 M3
s s
M1 M2 M3
s
M1 M2 M3
s
Thread 1
Lock Board
Ob1
Ob2
Ob1 Ob2
Ob3 Ob4
Ob4
Thread 2
Lock Board
Ob1 Ob3
Ob41
2
3
4
1
3
2
When a thread holds lock of object to
Access synchronized method, any other thread
trying to access another synchronized method
Should wait till the lock is released
JAVA9S.comJAVA9S.com
Locks - An example
Locks for Objects and class files work as hotel
rooms.
A person entering the room should have a lock
and any other person who needs to occupy that
room should wait till the lock is released.
JAVA9S.comJAVA9S.com
Why only Single lock?
bookTickets()
cancelTickets()
int totalTickets
Both methods can impact the value of TotalTickets variable.
To avoid conflict and confusion, One lock per object helps to
Keep threads away from manipulating instance variables
through methods.
Both methods can impact the value of TotalTickets variable.
To avoid conflict and confusion, One lock per object helps to
Keep threads away from manipulating instance variables
through methods.
Remember to keep the instance variables marked as private
in multithread environment to avoid manipulating them by threads
Remember to keep the instance variables marked as private
in multithread environment to avoid manipulating them by threads
Unnecessary code synchronization will effect the applications performance.Unnecessary code synchronization will effect the applications performance.
JAVA9S.comJAVA9S.com
Code Synchronization - DEMO
JAVA9S.comJAVA9S.com
www.JAVA9S.com
facebook.com/java9s
@java9s
JAVA9s
JAVA9S.comJAVA9S.com
Srinivas.java9s@gmail.com
CLICK HERE TO SUBSCRIBECLICK HERE TO SUBSCRIBE
Update your skill set..
Like to receive more
tutorials!!!
Like and Comment…..

More Related Content

Similar to Thread safety and code syncronization

07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
nimbalkarvikram966
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharp
Deivaa
 

Similar to Thread safety and code syncronization (20)

07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
07. Parbdhdjdjdjsjsjdjjdjdjjkdkkdkdkt.pptx
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
 
.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs
 
Java threading
Java threadingJava threading
Java threading
 
Sync, async and multithreading
Sync, async and multithreadingSync, async and multithreading
Sync, async and multithreading
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
Threads c sharp
Threads c sharpThreads c sharp
Threads c sharp
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
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...
 
MULTI THREADING.pptx
MULTI THREADING.pptxMULTI THREADING.pptx
MULTI THREADING.pptx
 
Java reentrant lock tutorial by jeetendra mandal
Java reentrant lock tutorial by jeetendra mandalJava reentrant lock tutorial by jeetendra mandal
Java reentrant lock tutorial by jeetendra mandal
 
Java tips
Java tipsJava tips
Java tips
 
Locks
LocksLocks
Locks
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
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,...
 

Recently uploaded

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 

Recently uploaded (20)

Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 

Thread safety and code syncronization

  • 1. Multithreading in Java – Part 3 Thread Safety By, Srinivas JAVA9S.comJAVA9S.com
  • 2. Need for Thread Safety DataThread 1 Thread 2 Total Balance = 500 Withdraw amount Wife = 450; Husband = 100 ??? No Funds available Java Application JAVA9S.comJAVA9S.com
  • 3. Need for Thread Safety Happybus.com Total Seats left: 3 No.of Seats wanted: 2 No.of Seats wanted: 2 When both of them get a chance to book at same time – then any one of them will get a message that there are no sufficient seats left JAVA9S.comJAVA9S.com
  • 4. Code – Without Thread Safety Demo JAVA9S.comJAVA9S.com
  • 5. Code Synchronization for thread safety• Code Synchronization helps in preventing multiple threads executing a code simultaneously. • Code Synchronization is implemented with the help of Locks. • A thread that is trying to access the code that is marked as Synchronized should acquire the lock from the object. • Locks: – Every object has a lock. Only one lock per object. – Every class has a lock. Only one lock per loaded class file. (For static methods) JAVA9S.comJAVA9S.com
  • 6. Synchronize - Few points • Synchronize can only be applied for methods and block of code. • Synchronize cannot be applied for classes and instance fields. Syntax: public synchronize void method(){ } public static synchronize void method{…} synchronize(this){…} JAVA9S.comJAVA9S.com
  • 7. Locks for Thread Safety M1 M2 M3 Methodss s M1 M2 M3 s s M1 M2 M3 s M1 M2 M3 s Thread 1 Lock Board Ob1 Ob2 Ob1 Ob2 Ob3 Ob4 Ob4 Thread 2 Lock Board Ob1 Ob3 Ob41 2 3 4 1 3 2 When a thread holds lock of object to Access synchronized method, any other thread trying to access another synchronized method Should wait till the lock is released JAVA9S.comJAVA9S.com
  • 8. Locks - An example Locks for Objects and class files work as hotel rooms. A person entering the room should have a lock and any other person who needs to occupy that room should wait till the lock is released. JAVA9S.comJAVA9S.com
  • 9. Why only Single lock? bookTickets() cancelTickets() int totalTickets Both methods can impact the value of TotalTickets variable. To avoid conflict and confusion, One lock per object helps to Keep threads away from manipulating instance variables through methods. Both methods can impact the value of TotalTickets variable. To avoid conflict and confusion, One lock per object helps to Keep threads away from manipulating instance variables through methods. Remember to keep the instance variables marked as private in multithread environment to avoid manipulating them by threads Remember to keep the instance variables marked as private in multithread environment to avoid manipulating them by threads Unnecessary code synchronization will effect the applications performance.Unnecessary code synchronization will effect the applications performance. JAVA9S.comJAVA9S.com
  • 10. Code Synchronization - DEMO JAVA9S.comJAVA9S.com
  • 12. CLICK HERE TO SUBSCRIBECLICK HERE TO SUBSCRIBE Update your skill set.. Like to receive more tutorials!!! Like and Comment…..