Author Topic:   Threds/Locks
Alkesh Nandanwar
ranch hand
posted April 12, 2000 10:56 AM             
Hi All,
Can a single Thread obtain multiple Locks at the same time?
I think the answer is YES but not vice versa. I mean a lock can have at the most just one thread.
Alkesh

Jesper Ottosson
ranch hand
posted April 12, 2000 12:03 PM             
yes, it can. If you write two nested synchronized() statements, the thread is obtaining two locks. And, you're right about the the-other-way-around stuff too.

maha anna
bartender
posted April 12, 2000 12:16 PM             
Yes. A thread can obtain the SAME OBJECT LOCK more than once.
It can also obtain MORE THAN 1 OBJECT's LOCK at a time.

In other words, a thread can have multipile locks in its hand. THese multiple locks may be obtainted by acquiring the same object's lock more than once OR obtaining one lock per object and more than 1 objects at the same time.

For example


case 1: lock_on_this and lock_onthis and lock_on_this

synchronized void m1 () {
synchronized(this) {
synchronized(this) {
}
}
}

case 2 : lock_on_this & lock on objectRef1 and lock_onObjectref2

synchronized void m1 () {
synchronized(objectRef1) {
synchronized(objectRef2) {
}
}
}


If you want more details please refer to this section in JLS
regds
maha anna

[This message has been edited by maha anna (edited April 12, 2000).]

Alkesh Nandanwar
ranch hand
posted April 12, 2000 02:48 PM             
Hi Jesper and Maha Anna,
Thank you for your detailed explanation.
Actually this is one of the question that an employeer from Silicon Valley asked me and I was confident about my answer.
He asked me one question about Weak Hashtable that I have posted in Java Intermediate Forum ( I am waiting for the answers ).
Garbage Collection and Threads seems to be very popular topics among employeers from Silicon Valley.
I will keep posting here.
Akesh

[This message has been edited by Alkesh Nandanwar (edited April 12, 2000).]

|