Java thread mechanism not safe in my case?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   George_Simple
Posted On:   Thursday, March 20, 2003 01:21 AM

Hi, everyone! Suppose a piece of code like this, -------- public synchronized void functionA(long preferedValue) { //do some thing wait(3000); //do some thing else } -------- Suppose thread A enters functionA and calls wait to release the lock of this object. Then thread B enters the functionA. Then for some reason, threadB release the lock of this object. Then thread A will get the lock of this object and continue to execute the codes "do some thing else". But at the same time, thread B still execute the code in functionA. So there are two threads in functionA. It means two threads own the same lock of this object. (The same as two thread   More>>
			
Hi, everyone!


Suppose a piece of code like this,


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

Suppose thread A enters functionA and calls wait to release
the lock of this object. Then thread B enters the functionA. Then for some reason, threadB release the lock of this object. Then thread A will get the lock of this object and continue to execute the codes "do some thing else". But at the same time, thread B still execute the code in functionA. So there are two threads in functionA. It means two threads own the same lock of this object. (The same as two threads are in the same synchronized block at the same time!!)

If I am correct, I think Java thread is not safe enough?
I think I am wrong. Which step of my scenario is wrong? Who can tell me?

I think maybe I am wrong at two points:

1. Can a thread release the lock of an object but still executes the codes in a synchronized region which is synchronized by the same object?

2. It is sure that when a thread tries to enter a synchronized region, it will check the status of the lock. But when a thread continues to execute the codes from a synchronized region (from the middle of the region and not
the beginning)from awakened up, as I showed in the above example. Will it still check the status of the lock?

regards,
George
   <<Less

Re: Java thread mechanism not safe in my case?

Posted By:   Brian_Glodde  
Posted On:   Thursday, March 20, 2003 01:37 PM

From the Java Language Specification:

» Threads and Monitors

» Synchronized Methods


Those 2 should clear up all your questions regarding the threading mechanisms.


Hope that helps!

About | Sitemap | Contact