Re: Deadlocks
getsanjay.sharma@gmail.com wrote:
Hello to all Java programmer out there.
I am currently reading about deadlocks and so wrote a small program
which would simulate a deadlock. But I have come across a very weird
behavior in the sense that it seems that Two threads are acquiring a
lock on an object at the same time. From what I know so far, each
object has a single lock object which a thread has to acquire to enter
the critical section. So why the given output which seems to say that
both Thread one and Thread two have acquired a lock on the same
object?
[snip]
/*
OUTPUT ->
[..]
ThreadOne ACQUIRED lock on 'ONE'
ThreadOne ACQUIRED lock on 'TWO'
ThreadOne : Setting values 20 and 30
ThreadOne GAVE UP lock on 'TWO'
ThreadOne GAVE UP lock on 'ONE'
ThreadTwo ACQUIRED lock on 'ONE'
ThreadTwo acquired lock on 'TWO'
ThreadTwo : The value is 50
ThreadTwo GAVE UP lock on 'TWO'
ThreadOne ACQUIRED lock on 'ONE'
ThreadOne ACQUIRED lock on 'TWO'
ThreadOne : Setting values 30 and 40
ThreadOne GAVE UP lock on 'TWO'
ThreadOne GAVE UP lock on 'ONE'
ThreadTwo GAVE UP lock on 'ONE'
[..]
*/
Links / Explanations / Comments / Suggestions would be really
appreciated.
Thanks and regards,
STS
I think the problem is your implicit assumption that after releasing a lock the
same thread continues execution and prints the line of text saying it gave up
the lock. This is not a valid assumption. The scheduler may well decide the
other thread has been waiting for some time and schedule that thread to run. So
the new thread prints its message saying it's got the lock before the original
thread gets to print its message saying it's released it.
If you want to guarantee that the prints to System.out occur in the correct
sequence they must also be guarded by the same synchronization object. That is,
instead of printing a message saying you've released the lock you should print
a message saying that the lock is about to be released.
--
Nigel Wade, System Administrator, Space Plasma Physics Group,
University of Leicester, Leicester, LE1 7RH, UK
E-mail : nmw@ion.le.ac.uk
Phone : +44 (0)116 2523548, Fax : +44 (0)116 2523555