0

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?

trincot
  • 317,000
  • 35
  • 244
  • 286
wbibile
  • 19
  • 3
  • 1
    By the way, you may be interested in [*JEP 412: Foreign Function & Memory API*](https://openjdk.java.net/jeps/412) being incubated in Java 17. – Basil Bourque Aug 09 '21 at 22:11
  • What you are attempting to do makes no sense. Java 8 is two LTS versions obsolete now. The foreign linker API in Java 16 is great but it's also dead now, in the sense that the API has changed with Java 17 and Java 16 is now past EOL. Either do whatever you want to do in Java 8 (which makes no sense, support for that ends in March) or do it in Java 17, the current LTS java. And no, there's no way to achieve what you are trying to do that will work in both Java 8 and Java 16. – user2959589 Oct 25 '21 at 02:46

0 Answers0