[concurrency-interest] AtomicReferenceFieldUpdater vs Unsafe

Rémi Forax forax at univ-mlv.fr
Thu Nov 17 08:47:52 EST 2011

On 11/17/2011 01:37 PM, Doug Lea wrote:
> On 11/17/11 06:10, √iktor Ҡlang wrote:
>> Right now it feels like if you're doing high-perf concurrency in this 
>> sense you
>> have to choose between:
>> A) Cache-trashing (and extra memory usage) because you went with 
>> AtomicLong/Ref
>> whatnot
>> B) CPU overhead caused by Atomic*Updaters and if you do any 
>> inheritance you'll
>> get even more checks each call (and extra mem usage due to padding).
>> C) Sacrifice cross-platform because you had to drop down to Unsafe to 
>> get the
>> correct machinecode emitted.
> Yes.
> The main underlying problem is a fundamental one: Java bytecodes
> support only two field read/write operations (getField/putField),
> plus an implicit mode argument for volatiles. However, there is no
> casField, or special r/w modes like releaseField. One level up,
> there is no syntax for "lvalue" operations on fields. So the
> only options are to directly invoke these lvalue operations
> via Unsafe, which require that you know the address of the field,
> or to use Updaters, that don't require the address, but must
> perform type checks and security checks that you have access to the
> field.

You can do the security check once exactly like the method handle API
does using a Lookup object.
I beleive that you can create a safe MethodHandle that will do a CAS
with an extra cost of a pointer comparison at runtime compared
with the unsafe compareAndSet.

> No one knows of any good alternatives. We tried for Java7
> to reduce need for either option by proposing Fences that
> would at least emulate the different memory modes, but that's
> also problematic enough to not be worth adopting.
> It's not hard to imagine some nicer syntax to support
> these operations (as in a.someField.compareAndSet(x, y))
> and also to perform class-loading-time validations (similarly
> to "quickening") and/or using invokeDynamic. But these matters
> never attain high enough priority when people consider syntax
> enhancements.
> Portability of Unsafe constructions is not really a problem.
> We frequently communicate with all production JVM implementors
> to help ensure that they are correctly supported.
> -Doug


More information about the Concurrency-interest mailing list