Re: synchronize vs gate
christopher@dailycrossword.com wrote:
What do y'all think about something like this:
boolean isBusy=false;
doSelfUpdate()
create temporary collection
isBusy=true;
update temporary collection from current collection
create temporary reference 'old' to current collection
point current collection reference to temporary collection
isBusy=false;
do stuff with 'old' collection
done
getCollection()
maxWait=10000
waited=0
while(isBusy && waited <maxWait) {
waited+=500
if(waited>=MaxWait) log error;
wait 500
}
return collection
done
Lew wrote:
Stick with the correct use of synchronization. You need to use concurrent
idioms to handle concurrent issues.
christopher@dailycrossword.com wrote:
thanx lew -- I don't care if the consumer gets an exact copy as long
as each copy it is internally consistent. Sorry if I did not phrase
Do you care if a consumer /never/ gets the updates from a producer? That is
the risk with the second idiom you provided.
my question well. I am not asking which runs faster or which takes
less time.
And I wasn't answering such a question. I was answering the question of
whether your so-called "gate" approach would work at all.
I am asking if I use synchronization doesn't each thread always have to wait for one and only one monitor? If I don't need
everyone to have an exact copy -- only an internally consistent one --
can't I simply gate the process (with an arbitrary wait and retry)?
No. If you do that the consumer might see none of the changes made by the
producer(s), ever, or might get an inconsistent view.
In my mind (such as it is) all the consuming threads are waiting at
the same time *only* while the singleton updates, rather than always
waiting for each other.
Read the threading tutorials on Sun and elsewhere.
I don't know what problem you imagine you are avoiding by not synchronizing,
but you aren't. A thread waits on a monitor only until another one releases
it. It is the "waiting for one and only one monitor" that makes the code
work; abandoning that is a recipe for disaster. Don't do it.
Your so-called "solution" to the non-existent "problem" will potentially cause
threads to run much slower than with correct synchronization, orders of
magnitude, several orders of magnitude, depending on your choice of "wait"
[sic] times, and also to get very wrong results.
For a related "broken solution" see
<http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html>
Use synchronization. Do not use your "gate" approach. And start using Java
for your examples.
<http://mindprod.com/jgloss/sscce.html>
<http://www.physci.org/codes/sscce.html>
Study threading and concurrency, and pay special attention to the Java "memory
model".
Forget the gate. Use synchronization.
--
Lew