Compare and Swap

Remi Forax forax at univ-mlv.fr
Wed Mar 30 22:52:33 UTC 2022


----- Original Message -----
> From: "Jasper Potts" <jasper.potts at hedera.com>
> To: "Maurizio Cimadamore" <maurizio.cimadamore at oracle.com>
> Cc: "panama-dev at openjdk.java.net'" <panama-dev at openjdk.java.net>
> Sent: Thursday, March 31, 2022 12:24:03 AM
> Subject: Re: Compare and Swap

> Thanks for the quick response Maurizio,
> 
> I will investigate that as an option. I have not used VarHandles directly yet
> but have seen how they are used in the implementation of
> java.util.concurrent.atomic.AtomicLongArray that I have been using for doing
> compare and swap with on-heap memory.
> 
> It seems like it would be expensive with all the boxing to Object types for call
> parameters but I guess the JDK might do a good job making it fast. I will need
> to do some JMH benchmarks and see. I am doing 10s of thousands a second so the
> performance matters.

There is no boxing, the methods of VarHandle have a polymorphic signature, which means the compiler will not do any boxing.

see https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/invoke/MethodHandle.html#sigpoly
and https://docs.oracle.com/javase/specs/jls/se18/html/jls-15.html#jls-15.12.3


> 
> Thanks
> 
> Jasper

Rémi

> 
>> On Mar 30, 2022, at 2:36 PM, Maurizio Cimadamore
>> <maurizio.cimadamore at oracle.com> wrote:
>> 
>> 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