VarHandles on non-int-sized fields and atomic operations
Aleksey Shipilev
aleksey.shipilev at oracle.com
Mon May 23 22:48:03 UTC 2016
On 05/24/2016 01:32 AM, Martin Buchholz wrote:
> On Mon, May 23, 2016 at 3:15 PM, Aleksey Shipilev
> <aleksey.shipilev at oracle.com> wrote:
>>> 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.
>
> But that's violating the abstraction boundary!
>
> You can use AtomicBoolean without being aware of whether you are
> actually generating 1-bit, 8-bit or 32-bit CASes. That's the JVM's
> job!
Even JVM is just a program and cannot perform miracles.
By the way, what exactly are you winning with 1-byte field in AtomicBoolean?
java.util.concurrent.atomic.AtomicBoolean object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 4 (object header) N/A
4 4 (object header) N/A
8 4 (object header) N/A
12 4 int AtomicBoolean.value 0
Instance size: 16 bytes
Making AtomicBoolean.value boolean would not decrease instance size,
because it will still be rounded towards 16 bytes, with 3 bytes
alignment shadow.
> It's going back to Evil Old C if we start having to encode our
> booleans using ints, just because of the instructions common on
> today's CPUs. It's true that users had to do this with Unsafe, but
> aren't VarHandles supposed to be a public high level replacement?
VarHandles is hardly "high level", pretty much like MethodHandles are
not high level. Those are building blocks to be used in library/runtime
code. What Unsafe accesses could do, VarHandles can also do (sometimes
more) -- without violating correctness and platform reliability.
> I think we're losing something if any VarHandles to primitive types
> fail to have a CAS.
Not "any", int/long/reference VarHandles still do CASes. Note that the
current API does not preclude implementing CASes for other types if you
can come up with a plausible mechanics of doing so.
The thing is, there does not seem to be a plausible fallback strategy
when platform cannot do a subword CAS. Or at least I cannot see it.
Artisanal Unsafe.compareAndSwapBoolean implementations are welcome :)
Thanks,
-Aleksey
More information about the core-libs-dev
mailing list