Vous êtes sur la page 1sur 11

Multithreading in Java Part 3 Thread Safety

JAVA9S.com

By, Srinivas Reddy.S

Need for Thread Safety


??? Total Balance = 500
Withdraw amount Wife = 450; Husband = 100 No Funds available Java Application

Thread 2 Thread 1 JAVA9S.com Data

Need for Thread Safety


Happybus.com

Total Seats left: 3

No.of Seats wanted: 2

No.of Seats wanted: 2

JAVA9S.com

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

Code Without Thread Safety Demo

JAVA9S.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.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.com

Locks for Thread Safety


Lock Board

Ob1

Ob2 Ob4

Thread 1
1

Thread 2 Ob1
sM
1 2 3 3 2 4 1

Lock Board

Ob1

Ob3 Ob4

s
M2 M3

Methods

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

Ob2
s
M1 M2 M3 M 1

Ob3
s
M2 M3

Ob4
s
M1

M 2

s
M3

JAVA9S.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.com

Why only Single lock?


bookTickets() cancelTickets() 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.
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.

int totalTickets

JAVA9S.com

Code Synchronization - DEMO

JAVA9S.com

www.JAVA9S.com

Srinivas.java9s@gmail.com
facebook.com/java9s

@java9s

JAVA9s
JAVA9S.com

Vous aimerez peut-être aussi