In our codebase we have an array-like datastructure class that allocates memory with sun.misc.Unsafe
so it can accept a long
as a size & index parameter. This class also uses the sun.misc.Unsafe
function compareAndSwapLong
to perform compare-and-swap (CAS) operations against elements of the array. This class produces un-silenceable warnings when compiled and per JEP 471 the functionality in sun.misc.Unsafe
is now deprecated, so we are looking to update it to use Java’s newer unsafe APIs.
Java’s VarHandle
class was introduced in JEP 193/Java 9 and is touted as a safe way to perform low-overhead CAS operations. However, it only appears to operate on existing safe datastructures; for example, to CAS an element of an array the docs show this example:
String[] sa = ...
VarHandle avh = MethodHandles.arrayElementVarHandle(String[].class);
boolean r = avh.compareAndSet(sa, 10, "expected", "new");
the docs then specify that the compareAndSet
call accepts an int
in the index position. Looking through the VarHandle
APIs, nothing jumps out as obviously exposing a CAS operation against memory allocated using either the old sun.misc.Unsafe
method or the new SegmentAllocater
interface introduced in JEP 454/Java 22. Where is this functionality exposed, if anywhere?