VarHandles on non-int-sized fields and atomic operations

Martin Buchholz martinrb at google.com
Mon May 23 23:20:46 UTC 2016


On Mon, May 23, 2016 at 3:48 PM, Aleksey Shipilev
<aleksey.shipilev at oracle.com> wrote:
> By the way, what exactly are you winning with 1-byte field in AtomicBoolean?

I'm not trying to replace the int field inside the AtomicBoolean with
a boolean - that's an implementation detail.
(Although I would take it if I could declare an atomic boolean inside
AtomicBoolean and let the JVM choose the best size for the platform.
It *is* a small weakness that we need to use the "int" type here in
java code)

I'm trying to allow regular programmers to declare their primitive
fields with the natural Java type and have all the atomic operations
available.

> 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 :)

As I said in a previous message, you can implement subword CAS using
fullword CAS in a loop.

cas8bit(expect, update) {
  for (;;) {
    fullword = atomicRead32()
    if ((fullword &0xff) != expect) return false;
    if (cas32(fullword, (fullword & ~0xff) | update) return true;
  }
}

but it would probably be more efficient if a fullword was allocated
for the subword field.



More information about the core-libs-dev mailing list