Compare and Swap

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Wed Mar 30 21:36:09 UTC 2022


Hi Jasper,
with both ByteBuffers and MemorySegments you can obtain a var handle for 
the access expression you want.

For instance, if you want a VarHandle which dereference ints on a 
MemorySegment, at a given offset, you can do:

VarHandle handle = MemoryHandles.varHandle(JAVA_INT)
int i = (int)handle.get(segment, offset);

Of course you can also use this var handle to perform a compare and 
swap, it's one of the supported modes - see:

https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/invoke/VarHandle.html#compareAndExchange(java.lang.Object...)
https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/invoke/VarHandle.html#compareAndSet(java.lang.Object...)

With ByteBuffer you can also get a var handle, using this:

https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/lang/invoke/MethodHandles.html#byteBufferViewVarHandle(java.lang.Class,java.nio.ByteOrder)

Have you tried these? Calling these on a VarHandle will just call the 
corresponding unsafe method.

Cheers
Maurizio

On 30/03/2022 22:18, Jasper Potts wrote:
> Hi,
>
> I would really like to replace our usage of misc.Unsafe but can’t seem to find a way to do the equivalent of compareAndSwapLong() on a MemorySegment. Today we use off-heap ByteBuffers and Unsafe to do atomic compare and swaps. It works great just sad to have to use Unsafe.
>
> Thanks
>
> Jasper


More information about the panama-dev mailing list