Beruflich Dokumente
Kultur Dokumente
JAVA9S.com
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
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
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
int totalTickets
JAVA9S.com
JAVA9S.com
www.JAVA9S.com
Srinivas.java9s@gmail.com
facebook.com/java9s
@java9s
JAVA9s
JAVA9S.com