VarHandles on non-int-sized fields and atomic operations
Aleksey Shipilev
aleksey.shipilev at oracle.com
Mon May 23 22:15:10 UTC 2016
On 05/23/2016 11:16 PM, Martin Buchholz wrote:
> 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?
Then you will get an exception trying to do the CAS.
> 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.
Mark that as "volatile int" :) Because if marking boolean field with
some "atomic" quantifier would blow up its storage to at least int,
that's what you get in the end anyhow.
> 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!)
Notice there is still no magic: we still can do CASes only on ints,
longs, references. (This is still a common denominator among all
supported platforms).
> My original motivation was to be able to replace an AtomicBoolean with
> a VarHandle to a boolean field.
No can do. AtomicBoolean, alas, should still keep "volatile int".
See the relevant discussion about this here:
http://mail.openjdk.java.net/pipermail/jmm-dev/2015-August/000193.html
Thanks,
-Aleksey
More information about the core-libs-dev
mailing list