이희승 (Trustin Lee) wrote:
The problem is we have so many properties which needs visibility
independent from each other.
Do we have a list of all the properties we need to protect? This could
be a good start to discuss about the best mechanism to use to protect them.
If we are going to use a lock, we will need as many lock objects as
the number of the properties, which is way too much IMO.
You can also synchronize the get() and set() methods, and you don't need
a lock anymore. Actually, this might be even more performant than using
volatile, if the property is read many times.
Or.. should we just return AtomicXYZ objects for all properties?
It will depend on the kind of property you want to protect.
public void increaseReadBytes(int increment) {
if (increment > 0) {
readBytes += increment;
lastReadTime = System.currentTimeMillis();
idleCountForBoth = 0;
idleCountForRead = 0;
}
}
readBytes += increment; should be atomic, and each assignment
operations should be visible to other threads (i.e. volatile is enough).
In this case, readBytes should be an AtomicInteger then, and you should
not be able to do a readBytes += increment. Volatile don't protect
against this operation (if you have a look at the way AtomicInteger is
written, it's really interesting to find that the stored value is
volatile, but that the increment operation calls a native method to
guarantee the concurrent access protection).
We can synchronize the whole operation (i.e. increaseReadBytes), but I
guess we won't get practical value from it as long as we don't expose
an explicit lock object for users.
What we want to do is to deliver a correct number of read bytes to the
user. Using an AtomicInteger for it should be enough.
--
--
cordialement, regards,
Emmanuel Lécharny
www.iktek.com
directory.apache.org