Forums Register Login

Syncrhonization woes

+Pie Number of slices to send: Send
Hi,

I have some code to pull an object out of a pool. The pool is just a vector and it lives in a singleton. I've synchronized both the obtain and release methods. Here is the code:



In my main class I created 500 Threads which all try and get an object, wait a bit and then release it. Since there are only 50 in the pool, I would expect to see the following:



The problem is though that I get the "Obtaining Object" printed out 50 times and then "Couldn't get Object, waiting" another 450 times.

I don't get why this happens as surely only one Thread can access the getObject at any one time.

Does anyone have any suggestions?

Thanks

Richard
+Pie Number of slices to send: Send
 

The problem is though that I get the "Obtaining Object" printed out 50 times and then "Couldn't get Object, waiting" another 450 times.

I don't get why this happens as surely only one Thread can access the getObject at any one time.



The wait() method releases the synchronization lock while it is waiting. This would make sense as it would not be possible for the releaseObject() method to be called if the lock were not free.

Henry
+Pie Number of slices to send: Send
With few exceptions, wait() should always be called in a loop: "while(x) wait()" rather than "if (x) wait()". The reason is that a Thread may be notified, but then before wait() returns, some other thread's wait() also returns and invalidates the condition. The "if(x) wait()" assumes that when wait() returns, x has become false, but it ain't necessarily so. The "while" version will not make this mistake.
+Pie Number of slices to send: Send
 

Originally posted by Ernest Friedman-Hill:
With few exceptions, wait() should always be called in a loop: "while(x) wait()" rather than "if (x) wait()". The reason is that a Thread may be notified, but then before wait() returns, some other thread's wait() also returns and invalidates the condition. The "if(x) wait()" assumes that when wait() returns, x has become false, but it ain't necessarily so. The "while" version will not make this mistake.



OK,

so changing the code to



Appears to have solved the problem, but please feel free to shout me down if this still isn't right!

Richard
+Pie Number of slices to send: Send
No, that's exactly what I meant!
Where all the women are strong, all the men are good looking and all the tiny ads are above average:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 805 times.
Similar Threads
problem in connectionpooling
another thread question
Threads 001
Regarding Notify
Threads and Synchronization examples
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 08:27:45.