Re: synchronize vs gate
christopher@dailycrossword.com wrote:
I have a singleton in a web service that provides a collection and
self-updates it on a periodic basis:
doSelfUpdate()
create temporary collection (time consuming)
syncronize
update temporary collection from current collection (fast)
create temporary reference 'old' to current collection
point current collection reference to temporary collection
end syncronize
do stuff with 'old' collection (time consuming)
done
Try providing an SSCCE for your example. The use of pseudocode to resolve a
Java question is not helpful.
getCollection()
synchronize
just waiting on monitor
end synchronize
return collection
done
It seems to me each thread accessing the getCollection method must
wait on the monitor every time it is accessed -- which is not what I
want. I just want to open and close the gate for a few milliseconds
while the self-update is being done. 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
IMHO this means each thread consuming getCollection is a tiny bit
slower because it has a condition that must be tested, but as a group
they are not waiting in line for the monitor. Is this right?
Assuming you mean the obvious transliteration to Java (e.g., that the producer
and consumer methods run in separate threads), your second form will not work.
getCollection() might return a version of collection containing none of the
updates from invocations of doSelfUpdate() in other threads. In a heavily
parallelized situation with multiple-core servers you very likely would end up
with corrupted results.
(Incidentally, "collection" is an inadvisable name for a variable.)
Another thing is that your "wait" times are entirely arbitrary (also
unspecified in your post). On what basis do you assess that any time you
choose is greater or less than the time it would take to acquire a monitor?
Stick with the correct use of synchronization. You need to use concurrent
idioms to handle concurrent issues.
--
Lew