VarHandles on non-int-sized fields and atomic operations
Martin Buchholz
martinrb at google.com
Mon May 23 20:16:11 UTC 2016
I believe C++ allows anything to be atomic using their atomic<> template.
Having the atomic annotation at the declaration site:
- makes it obvious to the human and the compiler that the data must be
accessed atomically.
- allows the compiler to lay out the data so that native cpu
instructions can access the data efficiently and atomically.
So it is likely that
atomic<short>
will be stored in a 32-bit field, since the cpu is likely to have a
32-bit cas, but not 16-bit cas.
With VarHandles, the declared fields are Ordinary Java Fields, so they
are likely to be layed out as with normal fields.
As a result, it looks like you can't do a cas with a VarHandle to a
short field.
If that's true, then the hardware is intruding into the API.
What happens when a platform with only a 64-bit CAS comes along?
Since atomic fields need different field layout from regular fields,
it seems to make sense to require that fields which will be accessed
via a VarHandle are clearly marked as being "atomic" in some way.
With the Unsafe API, we sort-of got this by requiring that fields be
volatile (although some users surely cheated here), and because there
was no Unsafe.compareAndSwapShort (but there is with VarHandles!)
My original motivation was to be able to replace an AtomicBoolean with
a VarHandle to a boolean field.
More information about the core-libs-dev
mailing list