Javaヒープ外にメモリを割り当てたり,読み込んだりする手段が提供された。MemorySegmentインタフェースを用いて,メモリセグメントを取得する。asByteBuffer()メソッドを使えば,ByteBufferのメソッドを使って操作できるため,これまでと同じように扱うことができる。以下のプログラムでは4バイトのメモリを割り当て,全バイトに0xFFを書き込んでいる。そして,その領域をint型で読み込んでintでの値を出力する。
import java.nio.ByteBuffer;
import jdk.incubator.foreign.MemorySegment;
public class ForeignMemoryExample
{
public static void main(final String[] args) throws Exception
{
try(MemorySegment segment = MemorySegment.allocateNative(4L))
{
ByteBuffer buffer = segment.asByteBuffer();
buffer.put(new byte[]{(byte)0xFF, (byte)0xFF, (byte)0xFF, (byte)0xFF});
int intValue = buffer.getInt(0);
System.out.println(String.format("int型での値は:%d", intValue));
}
}
}
これをコンパイルする。その際,module-info.javaを作成して,jdk.incubator.foreignモジュールを利用できるように記述しておく必要がある。
実行するには,次のコマンドを実行する。
java –add-modules jdk.incubator.foreign –enable-preview ForeignMemoryExample
実行すると,次のように出力されて,2の補数表現でintが取得された。
int型での値は:-1