VarHandle to Java Foreign Memory Segment without bounds checking in Java 21

95 Views Asked by At

I'm trying to update from Java 17 to 21, but I have problems with VarHandles from java.lang.foreign. I obtain VarHandle to the memory segment using

VarHandle varhandle = layout.varHandle(path)

But this method includes bounds checking on SequenceLayouts and IndexOutOfBounds exception. Other than that, I need the same behaviour as in Java 17.

How do I turn it off?

UPD: I need the method to work for any SequenceLayout

For example:

var innerLayout = MemoryLayout.structLayout(
  MemoryLayout.sequenceLayout(5, ValueLayout.JAVA_LONG).withName("a"),
  ValueLayout.JAVA_INT.withName("b"),
)

var layout = MemoryLayout.structLayout(
  MemoryLayout.sequenceLayout(n, innerLayout).withName("x"),
  MemoryLayout.sequenceLayout(m, innerLayout).withName("y"),
)

var xVarHandle = layout
  .varHandle(PathElement.groupElement("x"), PathElement.sequenceElement(), PathElement.groupElement("a"), PathElement.sequenceElement())

var yVarHandle = layout
  .varHandle(PathElement.groupElement("y"), PathElement.sequenceElement(), PathElement.groupElement("a"), PathElement.sequenceElement())
1

There are 1 best solutions below

0
Brian Goetz On

You're stuck in an XY problem; "turning off bounds checking" is not a thing. What is probably happening is that your VH calls are not being inlined, probably because of reasons such as those outlined by Jorn's comment:

If you're seeing a call to checkCustomized using a sampling profiler, then it looks like the VarHandle is not being optimized away. Make sure your VarHandle instances are constants, for instance by storing them in static final fields and using from there.