Re: Question whether a problem with race conditions exists in this case
On Dec 14, 10:26 pm, Eric Sosman <esos...@ieee-dot-org.invalid> wrote:
public class Node {
AtomicBoolean useNewValue = new AtomicBoolean(false);
Why isn't this `private'? Is something else going on that
you haven't told us about?
I just forgot to set it private.
private Object newValue = null;
private Object previousValue = null;
private Object lock = new Object();
What does `lock' buy you? Why not just synchronize on the
Node itself?
The purpose is only to indicate that some more fine-gtrained locking
would be used for the real thing instead of doing a synchronized(this)
{ ... } thing.
public void setNewValue(Object newValue, AtomicBoolean
useNewValueParam) {
synchronized(lock) {
if(this.useNewValue.get())
previousValue =
= this.newValue;
this.newValue = newValue;
// useNewValueParam is allways s=
et to false when setNewValue is called
I don't see why that would matter.
You mean that comment "useNewValueParam is allways set to false when
setNewValue is called"? To make sure that after setting the new value
the previous value is still returned on a call to get() until
useNewValue is set to true. This is why
if(this.useNewValue.get())
previousValue = this.newValue;
is done to make sure that the previous value is still returned in case
useNewValue was true before it was replaced with the new AtomicBoolean
through
this.useNewValue = useNewValueParam;
So `synchronized' is just to ensure that the single setNewValu=
e()
caller doesn't overlap any get() callers, is that right? (Nothing
wrong with that; I'm just trying to test my understanding of what
you're up to.)
Yes, exactly.
What's the larger problem you're trying to solve?
Well, I'm basically thinking about how to implement a database commit.
I don't use a database. Instead, the data is on the heap in a simple
list. When the commit is done, all the new values in all the nodes in
my list become visible at once (by changing useNewValue as explained)
to any thread calling get(). This way I get around changing the values
in a big big synchronized block which would cause quite some lock
contention.
Also, if only the elements in my list at position 1 and 3 have
changed, I only need to call setNewValue on the nodes at these
positions. I don't have to lock the entire list. If the values for the
elements at position 2 and 4 have to be changed at the same time, the
commit could be done in parallel to increase throughput (because there
are no overlapping regions) instead of locking the entire list.
--
Eric Sosman
esos...@ieee-dot-org.invalid