In Java 8 I'm using the following code to allocate and manage off-heap memory.
try {
String text = "test";
buffer.put(text.getBytes(StandardCharsets.UTF_8));
} finally {
// Release the memory
Optional.of(buffer).map(DirectBuffer.class::cast).map(DirectBuffer::cleaner).filter(Objects::nonNull).ifPresent(Cleaner::clean);
}
this imports classes sun.misc.Cleaner and sun.nio.ch.DirectBuffer; which are not available in Java 16. Under Java 16 I need to use the foreign memory API as follows, however this API is not available in Java 8.
try(MemorySegment s = MemorySegment.allocateNative(128))
{
//...
}
Is there a way to allocate off-heap memory and have my source compatible with Java 8 and 16?