2020-05-15

Java MemorySegment Example

MemorySegment

A memory segment is a contiguous region of memory. This can be either heap or off-heap memory. And, there are several ways to obtain a memory segment.

A memory segment backed by native memory is known as a native memory segment. It's created using one of the overloaded allocateNative methods.

Let's create a native memory segment of 200 bytes:

MemorySegment memorySegment = MemorySegment.allocateNative(200);
A memory segment can also be backed by an existing heap-allocated Java array. For example, we can  create an array memory segment from an array of long:


MemorySegment memorySegment = MemorySegment.ofArray(new long[100]);
Additionally, a memory segment can be backed by an existing Java ByteBuffer. This is known as a buffer memory segment:

MemorySegment memorySegment = MemorySegment.ofByteBuffer(ByteBuffer.allocateDirect(200));
Alternatively, we can use a memory-mapped file. This is known as a mapped memory segment. Let's define a 200-byte memory segment using a file path with read-write access:


MemorySegment memorySegment = MemorySegment.mapFromPath(
  Path.of("/tmp/memory.txt"), 200, FileChannel.MapMode.READ_WRITE);
A memory segment is attached to a specific thread. So, if any other thread requires access to the memory segment, it must gain access using the acquire method.

Also, a memory segment has spatial and temporal boundaries in terms of memory access:

Spatial boundary — the memory segment has lower and upper limits
Temporal boundary — governs creating, using, and closing a memory segment
Together, spatial and temporal checks ensure the safety of the JVM.

No comments:

Post a Comment