Tuesday, August 20, 2013

About Locking Mechanism in Threads....

About Locking Mechanism...
-------------------------------

Every object in java.. has.. a lock...At any time only one thread can
acquire a lock...,If one thread acquires lock.. all the threads should
need to wait for the lock.. only after the first thread releases the
lock.. second thread can acquire the lock....


When an object's lock is acquired by a thread.. ?
-------------------------------------------------------------------

When a thread enters synchronized method or block,
thread acquires the object's lock...

If any other thread wants to enter the synchronized method
or block...it needs to wait until the first thread releases it...

Assume Class Student has 3 methods...

a)first(synchronized method)
b)second(synchronized method
c)third

Assume there is a Student Object stu
stu = new Student();

When.. one thread XYZ enters first method.., first thread XYZ  acuqires
lock on stu object,so no other thread can enter... first or second
method... until  XYZ thread completes the first method...

But... the most important thing....,other threads can stilll enter
non synchronized method..........

Let me know if you have any doubts..........
























No comments:

Post a Comment