[concurrency-interest] AtomicReference weakCompareAndSet "Mayfailspuriously"?

Thomas Hawtin tackline at tackline.plus.com
Fri May 19 05:45:31 EDT 2006


Doug Lea wrote:
> Thomas Hawtin wrote:
>>
>> Is there any particular reason for not having a "weakGet" method? 
>> Going back to Hanson Char's example:
>>
>>  int maxLatencySnapshot = this.maxLatency.get();
>>  if (latency > maxLatencySnapshot) {
>>    if (this.maxLatency.weakCompareAndSet(maxLatencySnapshot, latency)) {
>>
>> Most of the gains that may be made from using weakCompareAndSet seem 
>> to be blown away by the get. (Sun's implementation doesn't seem to 
>> differentiate between weakCompareAndSet and compareAndSet, at the 
>> moment.)
>>
> 
> Generally, volatile-reads are cheap -- the main cost
> is suppressing optimizations/reorderings. On most machines,
> they don't generate machine-level barriers, and
> on the ones where they do (mainly: Itanium/IA64), they are the
> cheapest kind, and so barely measurable.
> 
> And the suppressed optimizations/orderings are exactly those you'd need to
> suppress in uses like this. Without this, a VM might (depending on
> context) forever cache a single read of the value, which would rarely
> be useful for an AtomicX. There may be a few use-cases for some kind of
> weakGet, but I think they are most rare.

As I understand it, weakCompareAndSet always gets to see the "current" 
value (unless it fails). An obvious constraints for weakGet is that it 
atomically reads a variable, is ordered with respect to other memory 
operations on that variable, but otherwise acts as an ordinary 
non-volatile memory operation (to adapt from weakCompareAndSet). 
(Actually you could go weaker than that - so long as weakCompareAndSet 
imposes some ordering on it. Say, weakGet returns some value that the 
variable had between the last ordering constraint and the next.)

So, for the particular variable it is ordered, which is enough to make 
the code correct. For other variables it is not ordered, which is enough 
to make most optimisations valid.

Tom Hawtin


More information about the Concurrency-interest mailing list