Click to See Complete Forum and Search --> : Question about synchronized and wait


George2
March 19th, 2003, 12:15 AM
Hi, everyone!


If a thread enters a piece of code that is marked
as synchronized, then the thread invoke wait(some time) in the same function.
Can other thread enter the same region that is marked as synchronized?
(I mean in the critical region there is no active thread but only waiting thread.)

For example:

--------
public synchronized void functionA ()
{
//check something
wait(3000);
//do some thing else
}
--------

If thread A enters function functionA and after "check something", it
wait for a notification. Then thread B tries to enter the same synchronized
function. Can thread B enters functionA when thread A is waiting for a
notification in functionA?


Thanks in advance,
George

dlorde
March 19th, 2003, 09:43 AM
Why not try it and see?

I'd do it myself if I wasn't so damned lazy...

Nemi
March 19th, 2003, 12:00 PM
Thread B will wait at functionA until someone calls notify() and releases thread A's lock or the wait timeout is reached.

George2
March 20th, 2003, 03:12 AM
Thanks, Nemi buddie!

I have referenced some materials and do not agree
with your opinion.

I think when thread A calles wait and it will release the
lock of this object and thread B will enters it.

You can reference,

--------
http://java.sun.com/j2se/1.3/docs/api/java/lang/Object.html#wait(long)
--------

especially,

--------
Note that the wait method, as it places the current thread into the wait set for this object, unlocks only this object; any other objects on which the current thread may be synchronized remain locked while the thread waits.
--------

What is your opinion?


regards,
George

Originally posted by Nemi
Thread B will wait at functionA until someone calls notify() and releases thread A's lock or the wait timeout is reached.

George2
March 20th, 2003, 03:15 AM
Thanks, dlorde buddie!

I have tested that thread B will enter the block. I
think the reason is, when a thread calls wait, it will release the lock(monitor) of this object. So thread B will enter the block.


Am I correct?


regards,
George




Originally posted by dlorde
Why not try it and see?

I'd do it myself if I wasn't so damned lazy...

Nemi
March 20th, 2003, 10:05 AM
You are indeed correct. The wait method causes the thread to relenquish any locks it may have on the object when it goes into the wait.

I was thinking of Thread.sleep(long millis). This method will not cause the thread to relenquish any locks it may have.

Good job picking that up.

George2
March 20th, 2003, 07:07 PM
Thanks, Nemi buddie!


George


Originally posted by Nemi
You are indeed correct. The wait method causes the thread to relenquish any locks it may have on the object when it goes into the wait.

I was thinking of Thread.sleep(long millis). This method will not cause the thread to relenquish any locks it may have.

Good job picking that up.