157. Tackling the slicing allocator
Let’s consider the following three Java regular int
arrays:
int[] arr1 = new int[]{1, 2, 3, 4, 5, 6};
int[] arr2 = new int[]{7, 8, 9};
int[] arr3 = new int[]{10, 11, 12, 13, 14};
Next, we want to allocate a memory segment to each of these arrays. A straightforward approach relies on Arena.allocateArray()
introduced in Problem 150:
try (Arena arena = Arena.ofConfined()) {
MemorySegment segment1
= arena.allocateArray(ValueLayout.JAVA_INT, arr1);
MemorySegment segment2
= arena.allocateArray(ValueLayout.JAVA_INT, arr2);
MemorySegment segment3
= arena.allocateArray(ValueLayout.JAVA_INT, arr3);
}
This approach allocates enough memory to accommodate each of the given arrays. But, sometimes, we want to allocate only a certain amount of memory. If this fixed amount is not enough, then we want to tackle the problem differently. For this, we can rely on a java.lang.foreign.SegmentAllocator
. Of course, there are...