Interface MemorySegment
There are two kinds of memory segments:
- Aheap segment is backed by, and provides access to, a region of memory inside the Java heap (an "on-heap" region).
- Anative segment is backed by, and provides access to, a region of memory outside the Java heap (an "off-heap" region).
ofArray(int[]) factory methods. These methods return a memory segment backed by the on-heap region that holds the specified Java array. Native segments can be obtained by calling one of theArena.allocate(long, long) factory methods, which return a memory segment backed by a newly allocated off-heap region with the given size and aligned to the given alignment constraint. Alternatively, native segments can be obtained bymapping a file into a new off-heap region (in some systems, this operation is sometimes referred to asmmap). Segments obtained in this way are calledmapped segments, and their contents can bepersisted andloaded to and from the underlying memory-mapped file.
Both kinds of segments are read and written using the same methods, known asaccess operations. An access operation on a memory segment always and only provides access to the region for which the segment was obtained.
Characteristics of memory segments
Every memory segment has anaddress, expressed as along value. The nature of a segment's address depends on the kind of the segment:- The address of a heap segment is not a physical address, but rather an offset within the region of memory which backs the segment. The region is inside the Java heap, so garbage collection might cause the region to be relocated in physical memory over time, but this is not exposed to clients of the
MemorySegmentAPI who see a stablevirtualized address for a heap segment backed by the region. A heap segment obtained from one of theofArray(int[])factory methods has an address of zero. - The address of a native segment (including mapped segments) denotes the physical address of the region of memory which backs the segment.
Every memory segment has amaximum byte alignment, expressed as along value. The maximum alignment is always a power of two, derived from the segment address, and the segment type, as explained in more detailbelow.
Every memory segment has asize. The size of a heap segment is derived from the Java array from which it is obtained. This size is predictable across Java runtimes. The size of a native segment is either passed explicitly (as inArena.allocate(long, long)) or derived from aMemoryLayout (as inSegmentAllocator.allocate(MemoryLayout)). The size of a memory segment is typically a positive number but may bezero, but never negative.
The address and size of a memory segment jointly ensure that access operations on the segment cannot falloutside the boundaries of the region of memory that backs the segment. That is, a memory segment hasspatial bounds.
Every memory segment is associated with ascope. This ensures that access operations on a memory segment cannot occur when the region of memory that backs the memory segment is no longer available (e.g., after the scope associated with the accessed memory segment is no longeralive). That is, a memory segment hastemporal bounds.
Finally, access operations on a memory segment can be subject to additional thread-confinement checks. Heap segments can be accessed from any thread. Conversely, native segments can only be accessed compatibly with theconfinement characteristics of the arena used to obtain them.
Accessing memory segments
A memory segment can be read or written using various access operations provided in this class (e.g.get(ValueLayout.OfInt, long)). Each access operation takes avalue layout, which specifies the size and shape of the value, and an offset, expressed in bytes. For instance, to read anint from a segment, usingdefault endianness, the following code can be used:MemorySegment segment = ...int value = segment.get(ValueLayout.JAVA_INT, 0);int value = segment.get(ValueLayout.JAVA_INT.withOrder(BIG_ENDIAN), 0);ValueLayout.varHandle() method can be used to obtain a var handle that can be used to get/set values represented by the given value layout on a memory segment at the given offset:VarHandle intAtOffsetHandle = ValueLayout.JAVA_INT.varHandle(); // (MemorySegment, long)int value = (int) intAtOffsetHandle.get(segment, 10L); // segment.get(ValueLayout.JAVA_INT, 10L)int array at a given logical index can be created as follows:VarHandle intAtOffsetAndIndexHandle = ValueLayout.JAVA_INT.arrayElementVarHandle(); // (MemorySegment, long, long)int value = (int) intAtOffsetAndIndexHandle.get(segment, 2L, 3L); // segment.get(ValueLayout.JAVA_INT, 2L + (3L * 4L)) Clients can also drop the base offset parameter, in order to make the access expression simpler. This can be used to implement access operations such asgetAtIndex(OfInt, long):
VarHandle intAtIndexHandle = MethodHandles.insertCoordinates(intAtOffsetAndIndexHandle, 1, 0L); // (MemorySegment, long)int value = (int) intAtIndexHandle.get(segment, 3L); // segment.getAtIndex(ValueLayout.JAVA_INT, 3L);Slicing memory segments
Memory segments supportslicing. Slicing a memory segment returns a new memory segment that is backed by the same region of memory as the original. The address of the sliced segment is derived from the address of the original segment, by adding an offset (expressed in bytes). The size of the sliced segment is either derived implicitly (by subtracting the specified offset from the size of the original segment), or provided explicitly. In other words, a sliced segment hasstricter spatial bounds than those of the original segment: Arena arena = ... MemorySegment segment = arena.allocate(100); MemorySegment slice = segment.asSlice(50, 10); slice.get(ValueLayout.JAVA_INT, 20); // Out of bounds! arena.close(); slice.get(ValueLayout.JAVA_INT, 0); // Already closed!segment, and is 10 bytes long. That is, the address of theslice issegment.address() + 50, and its size is 10. As a result, attempting to read an int value at offset 20 of theslice segment will result in an exception. Thetemporal bounds of the original segment is inherited by its slices; that is, when the scope associated withsegment is no longeralive,slice will also become inaccessible. A client might obtain aStream from a segment, which can then be used to slice the segment (according to a given element layout) and even allow multiple threads to work in parallel on disjoint segment slices (to do this, the segment has to beaccessible from multiple threads). The following code can be used to sum all int values in a memory segment in parallel:
try (Arena arena = Arena.ofShared()) { SequenceLayout SEQUENCE_LAYOUT = MemoryLayout.sequenceLayout(1024, ValueLayout.JAVA_INT); MemorySegment segment = arena.allocate(SEQUENCE_LAYOUT); int sum = segment.elements(ValueLayout.JAVA_INT).parallel() .mapToInt(s -> s.get(ValueLayout.JAVA_INT, 0)) .sum(); }Alignment
Access operations on a memory segment are constrained not only by the spatial and temporal bounds of the segment, but also by thealignment constraint of the value layout specified to the operation. An access operation can access only those offsets in the segment that denote addresses in physical memory that arealigned according to the layout. An address in physical memory isaligned according to a layout if the address is an integer multiple of the layout's alignment constraint. For example, the address 1000 is aligned according to an 8-byte alignment constraint (because 1000 is an integer multiple of 8), and to a 4-byte alignment constraint, and to a 2-byte alignment constraint; in contrast, the address 1004 is aligned according to a 4-byte alignment constraint, and to a 2-byte alignment constraint, but not to an 8-byte alignment constraint. Access operations are required to respect alignment because it can impact the performance of access operations, and can also determine which access operations are available at a given physical address. For instance,atomic access operations operations usingVarHandle are only permitted at aligned addresses. In addition, alignment applies to an access operation whether the segment being accessed is a native segment or a heap segment.If the segment being accessed is a native segment, then itsaddress in physical memory can be combined with the offset to obtain thetarget address in physical memory. The pseudo-function below demonstrates this:
boolean isAligned(MemorySegment segment, long offset, MemoryLayout layout) { return ((segment.address() + offset) % layout.byteAlignment()) == 0;}- A native segment with address 1000 can be accessed at offsets 0, 8, 16, 24, etc under an 8-byte alignment constraint, because the target addresses (1000, 1008, 1016, 1024) are 8-byte aligned. Access at offsets 1-7 or 9-15 or 17-23 is disallowed because the target addresses would not be 8-byte aligned.
- A native segment with address 1000 can be accessed at offsets 0, 4, 8, 12, etc under a 4-byte alignment constraint, because the target addresses (1000, 1004, 1008, 1012) are 4-byte aligned. Access at offsets 1-3 or 5-7 or 9-11 is disallowed because the target addresses would not be 4-byte aligned.
- A native segment with address 1000 can be accessed at offsets 0, 2, 4, 6, etc under a 2-byte alignment constraint, because the target addresses (1000, 1002, 1004, 1006) are 2-byte aligned. Access at offsets 1 or 3 or 5 is disallowed because the target addresses would not be 2-byte aligned.
- A native segment with address 1004 can be accessed at offsets 0, 4, 8, 12, etc under a 4-byte alignment constraint, and at offsets 0, 2, 4, 6, etc under a 2-byte alignment constraint. Under an 8-byte alignment constraint, it can be accessed at offsets 4, 12, 20, 28, etc.
- A native segment with address 1006 can be accessed at offsets 0, 2, 4, 6, etc under a 2-byte alignment constraint. Under a 4-byte alignment constraint, it can be accessed at offsets 2, 6, 10, 14, etc. Under an 8-byte alignment constraint, it can be accessed at offsets 2, 10, 18, 26, etc.
- A native segment with address 1007 can be accessed at offsets 0, 1, 2, 3, etc under a 1-byte alignment constraint. Under a 2-byte alignment constraint, it can be accessed at offsets 1, 3, 5, 7, etc. Under a 4-byte alignment constraint, it can be accessed at offsets 1, 5, 9, 13, etc. Under an 8-byte alignment constraint, it can be accessed at offsets 1, 9, 17, 25, etc.
The alignment constraint used to access a segment is typically dictated by the shape of the data structure stored in the segment. For example, if the programmer wishes to store a sequence of 8-byte values in a native segment, then the segment should be allocated by specifying an 8-byte alignment constraint, either viaArena.allocate(long, long) orSegmentAllocator.allocate(MemoryLayout). These factories ensure that the off-heap region of memory backing the returned segment has a starting address that is 8-byte aligned. Subsequently, the programmer can access the segment at the offsets of interest -- 0, 8, 16, 24, etc -- in the knowledge that every such access is aligned.
If the segment being accessed is a heap segment, then determining whether access is aligned is more complex. The address of the segment in physical memory is not known and is not even fixed (it may change when the segment is relocated during garbage collection). This means that the address cannot be combined with the specified offset to determine a target address in physical memory. Since the alignment constraintalways refers to alignment of addresses in physical memory, it is not possible in principle to determine if any offset in a heap segment is aligned. For example, suppose the programmer chooses an 8-byte alignment constraint and tries to access offset 16 in a heap segment. If the heap segment's address 0 corresponds to physical address 1000, then the target address (1016) would be aligned, but if address 0 corresponds to physical address 1004, then the target address (1020) would not be aligned. It is undesirable to allow access to target addresses that are aligned according to the programmer's chosen alignment constraint, but might not be predictably aligned in physical memory (e.g. because of platform considerations and/or garbage collection behavior).
In practice, the Java runtime lays out arrays in memory so that each n-byte element occurs at an n-byte aligned physical address. The runtime preserves this invariant even if the array is relocated during garbage collection. Access operations rely on this invariant to determine if the specified offset in a heap segment refers to an aligned address in physical memory. For example:
- The starting physical address of a
short[]array will be 2-byte aligned (e.g. 1006) so that successive short elements occur at 2-byte aligned addresses (e.g. 1006, 1008, 1010, 1012, etc). A heap segment backed by ashort[]array can be accessed at offsets 0, 2, 4, 6, etc under a 2-byte alignment constraint. The segment cannot be accessed atany offset under a 4-byte alignment constraint, because there is no guarantee that the target address would be 4-byte aligned, e.g., offset 0 would correspond to physical address 1006 while offset 1 would correspond to physical address 1007. Similarly, the segment cannot be accessed at any offset under an 8-byte alignment constraint, because there is no guarantee that the target address would be 8-byte aligned, e.g., offset 2 would correspond to physical address 1008 but offset 4 would correspond to physical address 1010. - The starting physical address of a
long[]array will be 8-byte aligned (e.g. 1000), so that successive long elements occur at 8-byte aligned addresses (e.g., 1000, 1008, 1016, 1024, etc.) A heap segment backed by along[]array can be accessed at offsets 0, 8, 16, 24, etc under an 8-byte alignment constraint. In addition, the segment can be accessed at offsets 0, 4, 8, 12, etc under a 4-byte alignment constraint, because the target addresses (1000, 1004, 1008, 1012) are 4-byte aligned. And, the segment can be accessed at offsets 0, 2, 4, 6, etc under a 2-byte alignment constraint, because the target addresses (e.g. 1000, 1002, 1004, 1006) are 2-byte aligned.
In other words, heap segments feature amaximum alignment which is derived from the size of the elements of the Java array backing the segment, as shown in the following table:
Heap segments can only be accessed using a layout whose alignment is smaller or equal to the maximum alignment associated with the heap segment. Attempting to access a heap segment using a layout whose alignment is greater than the maximum alignment associated with the heap segment will fail, as demonstrated in the following example:
Maximum alignment of heap segments Array type (of backing region) Maximum supported alignment (in bytes) boolean[]ValueLayout.JAVA_BOOLEAN.byteAlignment()byte[]ValueLayout.JAVA_BYTE.byteAlignment()char[]ValueLayout.JAVA_CHAR.byteAlignment()short[]ValueLayout.JAVA_SHORT.byteAlignment()int[]ValueLayout.JAVA_INT.byteAlignment()float[]ValueLayout.JAVA_FLOAT.byteAlignment()long[]ValueLayout.JAVA_LONG.byteAlignment()double[]ValueLayout.JAVA_DOUBLE.byteAlignment()
MemorySegment byteSegment = MemorySegment.ofArray(new byte[10]);byteSegment.get(ValueLayout.JAVA_INT, 0); // fails: ValueLayout.JAVA_INT.byteAlignment() > ValueLayout.JAVA_BYTE.byteAlignment()long[]), capable of supporting greater maximum alignment. More specifically, the maximum alignment associated withlong[] is set toValueLayout.JAVA_LONG.byteAlignment(), which is 8 bytes:MemorySegment longSegment = MemorySegment.ofArray(new long[10]);longSegment.get(ValueLayout.JAVA_INT, 0); // ok: ValueLayout.JAVA_INT.byteAlignment() <= ValueLayout.JAVA_LONG.byteAlignment()ValueLayout.JAVA_INT_UNALIGNED) have their alignment constraint set to 1:MemorySegment byteSegment = MemorySegment.ofArray(new byte[10]);byteSegment.get(ValueLayout.JAVA_INT_UNALIGNED, 0); // ok: ValueLayout.JAVA_INT_UNALIGNED.byteAlignment() == ValueLayout.JAVA_BYTE.byteAlignment()MemoryLayout layout = ...MemorySegment segment = ...boolean isAligned = segment.maxByteAlignment() >= layout.byteAlignment();Zero-length memory segments
When interacting withforeign functions, it is common for those functions to allocate a region of memory and return a pointer to that region. Modeling the region of memory with a memory segment is challenging because the Java runtime has no insight into the size of the region. Only the address of the start of the region, stored in the pointer, is available. For example, a C function with return typechar* might return a pointer to a region containing a singlechar value, or to a region containing an array ofchar values, where the size of the array might be provided in a separate parameter. The size of the array is not readily apparent to the code calling the foreign function and hoping to use its result. In addition to having no insight into the size of the region of memory backing a pointer returned from a foreign function, it also has no insight into the lifetime intended for said region of memory by the foreign function that allocated it. TheMemorySegment API useszero-length memory segments to represent:
- pointersreturned from a foreign function;
- pointerspassed by a foreign function to an upcall stub; and
- pointers read from a memory segment (more on that below).
- The size of the segment is zero. Any attempt to access these segments will fail with
IndexOutOfBoundsException. This is a crucial safety feature: as these segments are associated with a region of memory whose size is not known, any access operations involving these segments cannot be validated. In effect, a zero-length memory segmentwraps an address, and it cannot be used without explicit intent (see below); - The segment is associated with the global scope. Thus, while zero-length memory segments cannot be accessed directly, they can be passed, opaquely, to other pointer-accepting foreign functions.
To demonstrate how clients can work with zero-length memory segments, consider the case of a client that wants to read a pointer from some memory segment. This can be done via theget(AddressLayout, long) access method. This method accepts anaddress layout (e.g.ValueLayout.ADDRESS), the layout of the pointer to be read. For instance, on a 64-bit platform, the size of an address layout is 8 bytes. The access operation also accepts an offset, expressed in bytes, which indicates the position (relative to the start of the memory segment) at which the pointer is stored. The access operation returns a zero-length native memory segment, backed by a region of memory whose starting address is the 64-bit value read at the specified offset.
The returned zero-length memory segment cannot be accessed directly by the client: since the size of the segment is zero, any access operation would result in out-of-bounds access. Instead, the client must,unsafely, assign new spatial bounds to the zero-length memory segment. This can be done via thereinterpret(long)RESTRICTED method, as follows:
MemorySegment z = segment.get(ValueLayout.ADDRESS, ...); // size = 0 MemorySegment ptr = z.reinterpret(16); // size = 16 int x = ptr.getAtIndex(ValueLayout.JAVA_INT, 3); // ok In some cases, the client might additionally want to assign new temporal bounds to a zero-length memory segment. This can be done via thereinterpret(long, Arena, Consumer)RESTRICTED method, which returns a new native segment with the desired size and the same temporal bounds as those of the provided arena:
MemorySegment ptr = null; try (Arena arena = Arena.ofConfined()) { MemorySegment z = segment.get(ValueLayout.ADDRESS, ...); // size = 0, scope = always alive ptr = z.reinterpret(16, arena, null); // size = 16, scope = arena.scope() int x = ptr.getAtIndex(ValueLayout.JAVA_INT, 3); // ok } int x = ptr.getAtIndex(ValueLayout.JAVA_INT, 3); // throws IllegalStateException AddressLayout intArrPtrLayout = ValueLayout.ADDRESS.withTargetLayout( MemoryLayout.sequenceLayout(4, ValueLayout.JAVA_INT)); // layout for int (*ptr)[4] MemorySegment ptr = segment.get(intArrPtrLayout, ...); // size = 16 int x = ptr.getAtIndex(ValueLayout.JAVA_INT, 3); // ok All the methods that can be used to manipulate zero-length memory segments (reinterpret(long)RESTRICTED,reinterpret(Arena, Consumer)RESTRICTED,reinterpret(long, Arena, Consumer)RESTRICTED andAddressLayout.withTargetLayout(MemoryLayout)RESTRICTED) arerestricted methods, and should be used with caution: assigning a segment incorrect spatial and/or temporal bounds could result in a VM crash when attempting to access the memory segment.
- Implementation Requirements:
- Implementations of this interface are immutable, thread-safe andvalue-based.
- Since:
- 22
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic interfaceA scope models thelifetime of all the memory segments associated with it.Field Summary
FieldsModifier and TypeFieldDescriptionstatic finalMemorySegmentA zero-length native segment modelling theNULLaddress.Method Summary
Modifier and TypeMethodDescriptionlongaddress()Returns the address of this memory segment.Wraps this segment in aByteBuffer.asOverlappingSlice(MemorySegment other) Returns a slice of this segment that is the overlap between this and the providedsegment.Returns a read-only view of this segment.asSlice(long offset) Returns a slice of this memory segment, at the given offset.asSlice(long offset, long newSize) Returns a slice of this memory segment, at the given offset.asSlice(long offset, long newSize, long byteAlignment) Returns a slice of this memory segment, at the given offset, with the providedalignment constraint.asSlice(long offset,MemoryLayout layout) Returns a slice of this memory segment with the given layout, at the given offset.longbyteSize()Returns the size (in bytes) of this memory segment.static voidcopy(MemorySegment srcSegment, long srcOffset,MemorySegment dstSegment, long dstOffset, long bytes) Performs a bulk copy from source segment to destination segment.static voidcopy(MemorySegment srcSegment,ValueLayout srcElementLayout, long srcOffset,MemorySegment dstSegment,ValueLayout dstElementLayout, long dstOffset, long elementCount) Performs a bulk copy from source segment to destination segment.static voidcopy(MemorySegment srcSegment,ValueLayout srcLayout, long srcOffset,Object dstArray, int dstIndex, int elementCount) Copies a number of elements from a source memory segment to a destination array.static voidcopy(Object srcArray, int srcIndex,MemorySegment dstSegment,ValueLayout dstLayout, long dstOffset, int elementCount) Copies a number of elements from a source array to a destination memory segment.copyFrom(MemorySegment src) Performs a bulk copy from the given source segment to this segment.elements(MemoryLayout elementLayout) Returns a sequentialStreamover disjoint slices (whose size matches thatof the specified layout) in this segment.booleanCompares the specified object with this memory segment for equality.fill(byte value) Fills the contents of this memory segment with the given value.voidforce()Forces any changes made to the contents of this mapped segment to be written tothe storage device described by the mapped segment's file descriptor.get(AddressLayout layout, long offset) Reads an address from this segment at the given offset, with the given layout.booleanget(ValueLayout.OfBoolean layout, long offset) Reads a boolean from this segment at the given offset, with the given layout.byteget(ValueLayout.OfByte layout, long offset) Reads a byte from this segment at the given offset, with the given layout.charget(ValueLayout.OfChar layout, long offset) Reads a char from this segment at the given offset, with the given layout.doubleget(ValueLayout.OfDouble layout, long offset) Reads a double from this segment at the given offset, with the given layout.floatget(ValueLayout.OfFloat layout, long offset) Reads a float from this segment at the given offset, with the given layout.intget(ValueLayout.OfInt layout, long offset) Reads an int from this segment at the given offset, with the given layout.longget(ValueLayout.OfLong layout, long offset) Reads a long from this segment at the given offset, with the given layout.shortget(ValueLayout.OfShort layout, long offset) Reads a short from this segment at the given offset, with the given layout.getAtIndex(AddressLayout layout, long index) Reads an address from this segment at the given at the given index, scaled by thegiven layout size.booleangetAtIndex(ValueLayout.OfBoolean layout, long index) Reads a boolean from this segment at the given index, scaled by the givenlayout size.bytegetAtIndex(ValueLayout.OfByte layout, long index) Reads a byte from this segment at the given index, scaled by the givenlayout size.chargetAtIndex(ValueLayout.OfChar layout, long index) Reads a char from this segment at the given index, scaled by the givenlayout size.doublegetAtIndex(ValueLayout.OfDouble layout, long index) Reads a double from this segment at the given index, scaled by the givenlayout size.floatgetAtIndex(ValueLayout.OfFloat layout, long index) Reads a float from this segment at the given index, scaled by the givenlayout size.intgetAtIndex(ValueLayout.OfInt layout, long index) Reads an int from this segment at the given index, scaled by the givenlayout size.longgetAtIndex(ValueLayout.OfLong layout, long index) Reads a long from this segment at the given index, scaled by the givenlayout size.shortgetAtIndex(ValueLayout.OfShort layout, long index) Reads a short from this segment at the given index, scaled by the givenlayout size.getString(long offset) Reads a null-terminated string from this segment at the given offset, using theUTF-8 charset.Reads a null-terminated string from this segment at the given offset, using theprovided charset.inthashCode()Returns the hash code value for this memory segment.heapBase()Returns the Java object stored in the on-heap region of memory backing this memorysegment, if any.booleanisAccessibleBy(Thread thread) Returnstrueif this segment can be accessed from the provided thread.booleanisLoaded()Determines whether all the contents of this mapped segment are resident in physicalmemory.booleanisMapped()Returnstrueif this segment is a mapped segment.booleanisNative()Returnstrueif this segment is a native segment.booleanReturnstrue, if this segment is read-only.voidload()Loads the contents of this mapped segment into physical memory.longReturns themaximum byte alignmentassociated with this memory segment.longmismatch(MemorySegment other) Finds and returns the offset, in bytes, of the first mismatch betweenthis segment and the given other segment.static longmismatch(MemorySegment srcSegment, long srcFromOffset, long srcToOffset,MemorySegment dstSegment, long dstFromOffset, long dstToOffset) Finds and returns the relative offset, in bytes, of the first mismatch between thesource and the destination segments.staticMemorySegmentofAddress(long address) Creates a zero-length native segment from the givenaddress value.staticMemorySegmentofArray(byte[] byteArray) Creates a heap segment backed by the on-heap region of memory that holds the givenbyte array.staticMemorySegmentofArray(char[] charArray) Creates a heap segment backed by the on-heap region of memory that holds the givenchar array.staticMemorySegmentofArray(double[] doubleArray) Creates a heap segment backed by the on-heap region of memory that holds the givendouble array.staticMemorySegmentofArray(float[] floatArray) Creates a heap segment backed by the on-heap region of memory that holds the givenfloat array.staticMemorySegmentofArray(int[] intArray) Creates a heap segment backed by the on-heap region of memory that holds the givenint array.staticMemorySegmentofArray(long[] longArray) Creates a heap segment backed by the on-heap region of memory that holds the givenlong array.staticMemorySegmentofArray(short[] shortArray) Creates a heap segment backed by the on-heap region of memory that holds the givenshort array.staticMemorySegmentCreates a memory segment that is backed by the same region of memory that backsthe givenBufferinstance.reinterpret(long newSize) Restricted.Returns a new memory segment that has the same address and scope as this segment,but with the provided size.reinterpret(long newSize,Arena arena,Consumer<MemorySegment> cleanup) Restricted.Returns a new segment with the same address as this segment, but with the providedsize and the provided arena's scope.reinterpret(Arena arena,Consumer<MemorySegment> cleanup) Restricted.Returns a new memory segment with the same address and size as this segment, butwith the provided arena's scope.scope()Returns the scope associated with this memory segment.voidset(AddressLayout layout, long offset,MemorySegment value) Writes an address into this segment at the given offset, with the given layout.voidset(ValueLayout.OfBoolean layout, long offset, boolean value) Writes a boolean into this segment at the given offset, with the given layout.voidset(ValueLayout.OfByte layout, long offset, byte value) Writes a byte into this segment at the given offset, with the given layout.voidset(ValueLayout.OfChar layout, long offset, char value) Writes a char into this segment at the given offset, with the given layout.voidset(ValueLayout.OfDouble layout, long offset, double value) Writes a double into this segment at the given offset, with the given layout.voidset(ValueLayout.OfFloat layout, long offset, float value) Writes a float into this segment at the given offset, with the given layout.voidset(ValueLayout.OfInt layout, long offset, int value) Writes an int into this segment at the given offset, with the given layout.voidset(ValueLayout.OfLong layout, long offset, long value) Writes a long into this segment at the given offset, with the given layout.voidset(ValueLayout.OfShort layout, long offset, short value) Writes a short into this segment at the given offset, with the given layout.voidsetAtIndex(AddressLayout layout, long index,MemorySegment value) Writes an address into this segment at the given index, scaled by the givenlayout size.voidsetAtIndex(ValueLayout.OfBoolean layout, long index, boolean value) Writes a boolean into this segment at the given index, scaled by the givenlayout size.voidsetAtIndex(ValueLayout.OfByte layout, long index, byte value) Writes a byte into this segment at the given index, scaled by the given layout size.voidsetAtIndex(ValueLayout.OfChar layout, long index, char value) Writes a char into this segment at the given index, scaled by the givenlayout size.voidsetAtIndex(ValueLayout.OfDouble layout, long index, double value) Writes a double into this segment at the given index, scaled by the givenlayout size.voidsetAtIndex(ValueLayout.OfFloat layout, long index, float value) Writes a float into this segment at the given index, scaled by the givenlayout size.voidsetAtIndex(ValueLayout.OfInt layout, long index, int value) Writes an int into this segment at the given index, scaled by the givenlayout size.voidsetAtIndex(ValueLayout.OfLong layout, long index, long value) Writes a long into this segment at the given index, scaled by the givenlayout size.voidsetAtIndex(ValueLayout.OfShort layout, long index, short value) Writes a short into this segment at the given index, scaled by the givenlayout size.voidWrites the given string into this segment at the given offset, converting it to a null-terminated byte sequence using theUTF-8 charset.voidWrites the given string into this segment at the given offset, converting it to anull-terminated byte sequence using the provided charset.spliterator(MemoryLayout elementLayout) Returns a spliterator for this memory segment.byte[]toArray(ValueLayout.OfByte elementLayout) Copy the contents of this memory segment into a new byte array.char[]toArray(ValueLayout.OfChar elementLayout) Copy the contents of this memory segment into a new char array.double[]toArray(ValueLayout.OfDouble elementLayout) Copy the contents of this memory segment into a new double array.float[]toArray(ValueLayout.OfFloat elementLayout) Copy the contents of this memory segment into a new float array.int[]toArray(ValueLayout.OfInt elementLayout) Copy the contents of this memory segment into a new int array.long[]toArray(ValueLayout.OfLong elementLayout) Copy the contents of this memory segment into a new long array.short[]toArray(ValueLayout.OfShort elementLayout) Copy the contents of this memory segment into a new short array.voidunload()Unloads the contents of this mapped segment from physical memory.
Field Details
NULL
A zero-length native segment modelling theNULLaddress. Equivalent toMemorySegment.ofAddress(0L).Themaximum byte alignment forthe
NULLsegment is of 262.
Method Details
address
long address()Returns the address of this memory segment.- API Note:
- When using this method to pass a segment address to some external operation (e.g. a JNI function), clients must ensure that the segment is keptreachable for the entire duration of the operation. A failure to do so might result in the premature deallocation of the region of memory backing the memory segment, in case the segment has been allocated with anautomatic arena.
- Returns:
- the address of this memory segment
heapBase
Returns the Java object stored in the on-heap region of memory backing this memorysegment, if any. For instance, if this memory segment is a heap segment createdwith theofArray(byte[])factory method, this method will return thebyte[]object which was used to obtain the segment. This method returnsan emptyOptionalvalue if either this segment is anative segment, or if this segment isread-only.- Returns:
- the Java object associated with this memory segment, if any
spliterator
Returns a spliterator for this memory segment. The returned spliterator reportsSpliterator.SIZED,Spliterator.SUBSIZED,Spliterator.IMMUTABLE,Spliterator.NONNULLandSpliterator.ORDEREDcharacteristics.The returned spliterator splits this segment according to the specified elementlayout; that is, if the supplied layout has size N, then calling
Spliterator.trySplit()will result in a spliterator serving approximatelyS/Nelements (depending on whether N is even or not), whereSisthe size of this segment. As such, splitting is possible as long asS/N >= 2. The spliterator returns segments that have the same lifetime asthat of this segment.The returned spliterator effectively allows to slice this segment into disjointslices, which can then be processed in parallelby multiple threads.
- Parameters:
elementLayout- the layout to be used for splitting- Returns:
- the element spliterator for this segment
- Throws:
IllegalArgumentException- ifelementLayout.byteSize() == 0IllegalArgumentException- ifbyteSize() % elementLayout.byteSize() != 0IllegalArgumentException- ifelementLayout.byteSize() % elementLayout.byteAlignment() != 0IllegalArgumentException- if this segment isincompatible with the alignment constraint in the provided layout.
elements
Returns a sequentialStreamover disjoint slices (whose size matches thatof the specified layout) in this segment. Calling this method is equivalent tothe following code:StreamSupport.stream(segment.spliterator(elementLayout), false);- Parameters:
elementLayout- the layout to be used for splitting- Returns:
- a sequential
Streamover disjoint slices in this segment - Throws:
IllegalArgumentException- ifelementLayout.byteSize() == 0IllegalArgumentException- ifbyteSize() % elementLayout.byteSize() != 0IllegalArgumentException- ifelementLayout.byteSize() % elementLayout.byteAlignment() != 0IllegalArgumentException- if this segment isincompatible with the alignment constraint in the provided layout
scope
MemorySegment.Scope scope()Returns the scope associated with this memory segment.- Returns:
- the scope associated with this memory segment
isAccessibleBy
Returnstrueif this segment can be accessed from the provided thread.- Parameters:
thread- the thread to be tested- Returns:
trueif this segment can be accessed from the provided thread
byteSize
long byteSize()Returns the size (in bytes) of this memory segment.- Returns:
- the size (in bytes) of this memory segment
maxByteAlignment
long maxByteAlignment()Returns themaximum byte alignmentassociated with this memory segment.The returned alignment is always a power of two and is derived fromthe segmentaddress() and, if it is a heap segment,the type of thebacking heap storage.
This method can be used to ensure that a segment is sufficiently alignedwith a layout:
MemoryLayout layout = ...MemorySegment segment = ...if (segment.maxByteAlignment() < layout.byteAlignment()) { // Take action (e.g. throw an Exception)}- Returns:
- themaximum byte alignmentassociated with this memory segment
- Since:
- 23
asSlice
Returns a slice of this memory segment, at the given offset. The returnedsegment's address is the address of this segment plus the given offset;its size is specified by the given argument.Equivalent to the following code:
asSlice(offset, newSize, 1);If this segment isread-only,the returned segment is alsoread-only.
The returned memory segment shares a region of backing memory with this segment.Hence, no memory will be allocated or freed by this method.
- Parameters:
offset- The new segment base offset (relative to the address of this segment), specified in bytesnewSize- The new segment size, specified in bytes- Returns:
- a slice of this memory segment
- Throws:
IndexOutOfBoundsException- ifoffset < 0,offset > byteSize(),newSize < 0, ornewSize > byteSize() - offset- See Also:
asSlice
Returns a slice of this memory segment, at the given offset, with the providedalignment constraint. The returned segment's address is the address of thissegment plus the given offset; its size is specified by the given argument.If this segment isread-only,the returned segment is alsoread-only.
The returned memory segment shares a region of backing memory with this segment.Hence, no memory will be allocated or freed by this method.
- Parameters:
offset- The new segment base offset (relative to the address of this segment), specified in bytesnewSize- The new segment size, specified in bytesbyteAlignment- The alignment constraint (in bytes) of the returned slice- Returns:
- a slice of this memory segment
- Throws:
IndexOutOfBoundsException- ifoffset < 0,offset > byteSize(),newSize < 0, ornewSize > byteSize() - offsetIllegalArgumentException- if this segment cannot be accessed atoffsetunder the provided alignment constraintIllegalArgumentException- ifbyteAlignment <= 0, or ifbyteAlignmentis not a power of 2
asSlice
Returns a slice of this memory segment with the given layout, at the given offset.The returned segment's address is the address of this segment plus the givenoffset; its size is the same as the size of the provided layout.Equivalent to the following code:
asSlice(offset, layout.byteSize(), layout.byteAlignment());If this segment isread-only,the returned segment is alsoread-only.
The returned memory segment shares a region of backing memory with this segment.Hence, no memory will be allocated or freed by this method.
- Parameters:
offset- The new segment base offset (relative to the address of this segment), specified in byteslayout- The layout of the segment slice- Returns:
- a slice of this memory segment
- Throws:
IndexOutOfBoundsException- ifoffset < 0,offset > byteSize(), orlayout.byteSize() > byteSize() - offsetIllegalArgumentException- if this segment cannot be accessed atoffsetunder the alignment constraint specified bylayout- See Also:
asSlice
Returns a slice of this memory segment, at the given offset. The returnedsegment's address is the address of this segment plus the given offset; its sizeis computed by subtracting the specified offset from this segment size.Equivalent to the following code:
asSlice(offset, byteSize() - offset);If this segment isread-only,the returned segment is alsoread-only.
The returned memory segment shares a region of backing memory with this segment.Hence, no memory will be allocated or freed by this method.
- Parameters:
offset- The new segment base offset (relative to the address of this segment), specified in bytes- Returns:
- a slice of this memory segment
- Throws:
IndexOutOfBoundsException- ifoffset < 0, oroffset > byteSize()- See Also:
reinterpret
reinterpretis arestricted method of the Java platform.Programs can only usereinterpretwhen access to restricted methods is enabled.Restricted methods are unsafe, and, if used incorrectly, might crash the JVM or result in memory corruption.Returns a new memory segment that has the same address and scope as this segment,but with the provided size.If this segment isread-only,the returned segment is alsoread-only.
The returned memory segment shares a region of backing memory with this segment.Hence, no memory will be allocated or freed by this method.
- Parameters:
newSize- the size of the returned segment- Returns:
- a new memory segment that has the same address and scope as this segment, but the new provided size
- Throws:
IllegalArgumentException- ifnewSize < 0UnsupportedOperationException- if this segment is not anative segmentIllegalCallerException- if the caller is in a module that does not have native access enabled
reinterpret
reinterpretis arestricted method of the Java platform.Programs can only usereinterpretwhen access to restricted methods is enabled.Restricted methods are unsafe, and, if used incorrectly, might crash the JVM or result in memory corruption.Returns a new memory segment with the same address and size as this segment, butwith the provided arena's scope. As such, the returned segment cannot be accessedafter the provided arena has been closed. Moreover, the returned segment can beaccessed compatibly with the confinement restrictions associated with the providedarena: that is, if the provided arena is aconfined arena,the returned segment can only be accessed by the arena's owner thread, regardlessof the confinement restrictions associated with this segment. In other words, thismethod returns a segment that can be used as any other segment allocated using theprovided arena. However, the returned segment is backed by the same memory regionas that of the original segment. As such, the region of memory backing thereturned segment is deallocated only when this segment's arena is closed.This might lead touse-after-free issues, as the returned segment can beaccessedafter its region of memory has been deallocated via thissegment's arena.Clients can specify an optional cleanup action that should be executed when theprovided arena's scope becomes invalid. This cleanup action receives a fresh memorysegment that is obtained from this segment as follows:
That is, the cleanup action receives a segment that is associated with the globalarena's scope, and is accessible from any thread. The size of the segment acceptedby the cleanup action isMemorySegment cleanupSegment = MemorySegment.ofAddress(this.address()) .reinterpret(byteSize());byteSize().If this segment isread-only,the returned segment is alsoread-only.
The returned memory segment shares a region of backing memory with this segment.Hence, no memory will be allocated or freed by this method.
- API Note:
- The cleanup action (if present) should take care not to leak the received segment to external clients that might access the segment after its backing region of memory is no longer available. Furthermore, if the provided arena is anautomatic arena, the cleanup action must not prevent the arena from becomingunreachable. A failure to do so will permanently prevent the regions of memory allocated by the automatic arena from being deallocated.
- Parameters:
arena- the arena to be associated with the returned segmentcleanup- the cleanup action that should be executed when the provided arena is closed (can benull)- Returns:
- a new memory segment with unbounded size
- Throws:
IllegalStateException- ifarena.scope().isAlive() == falseUnsupportedOperationException- if this segment is not anative segmentIllegalCallerException- if the caller is in a module that does not have native access enabled
reinterpret
reinterpretis arestricted method of the Java platform.Programs can only usereinterpretwhen access to restricted methods is enabled.Restricted methods are unsafe, and, if used incorrectly, might crash the JVM or result in memory corruption.Returns a new segment with the same address as this segment, but with the providedsize and the provided arena's scope. As such, the returned segment cannot beaccessed after the provided arena has been closed. Moreover, if the returnedsegment can be accessed compatibly with the confinement restrictions associatedwith the provided arena: that is, if the provided arena is aconfined arena,the returned segment can only be accessed by the arena's owner thread, regardlessof the confinement restrictions associated with this segment. In other words, thismethod returns a segment that can be used as any other segment allocated using theprovided arena. However, the returned segment is backed by the same memory regionas that of the original segment. As such, the region of memory backing thereturned segment is deallocated only when this segment's arena is closed.This might lead touse-after-free issues, as the returned segment can beaccessedafter its region of memory has been deallocated via thissegment's arena.Clients can specify an optional cleanup action that should be executed when theprovided arena's scope becomes invalid. This cleanup action receives a fresh memorysegment that is obtained from this segment as follows:
That is, the cleanup action receives a segment that is associated with the globalarena's scope, and is accessible from any thread. The size of the segment acceptedby the cleanup action isMemorySegment cleanupSegment = MemorySegment.ofAddress(this.address()) .reinterpret(newSize);newSize.If this segment isread-only,the returned segment is alsoread-only.
The returned memory segment shares a region of backing memory with this segment.Hence, no memory will be allocated or freed by this method.
- API Note:
- The cleanup action (if present) should take care not to leak the received segment to external clients that might access the segment after its backing region of memory is no longer available. Furthermore, if the provided arena is anautomatic arena, the cleanup action must not prevent the arena from becomingunreachable. A failure to do so will permanently prevent the regions of memory allocated by the automatic arena from being deallocated.
- Parameters:
newSize- the size of the returned segmentarena- the arena to be associated with the returned segmentcleanup- the cleanup action that should be executed when the provided arena is closed (can benull).- Returns:
- a new segment that has the same address as this segment, but with the new size and its scope set to that of the provided arena.
- Throws:
UnsupportedOperationException- if this segment is not anative segmentIllegalArgumentException- ifnewSize < 0IllegalStateException- ifarena.scope().isAlive() == falseIllegalCallerException- if the caller is in a module that does not have native access enabled
isReadOnly
boolean isReadOnly()Returnstrue, if this segment is read-only.- Returns:
true, if this segment is read-only- See Also:
asReadOnly
MemorySegment asReadOnly()Returns a read-only view of this segment.The resulting segment will be identical to this one, but attempts to overwrite thecontents of the returned segment will cause runtime exceptions.- Returns:
- a read-only view of this segment
- See Also:
isNative
boolean isNative()Returnstrueif this segment is a native segment.A native segment is created e.g. using the
Arena.allocate(long, long)(and related) factory, or bywrapping adirect buffer.- Returns:
trueif this segment is a native segment
isMapped
boolean isMapped()Returnstrueif this segment is a mapped segment.A mapped memory segment is created e.g. using theFileChannel.map(FileChannel.MapMode, long, long, Arena)factory, or bywrapping amapped byte buffer.- Returns:
trueif this segment is a mapped segment
asOverlappingSlice
Returns a slice of this segment that is the overlap between this and the providedsegment.Two segments
S1andS2are said to overlap if it is possible tofind at least two slicesL1(fromS1) andL2(fromS2) that are backed by the same region of memory. As such, it isnot possible for anative segment to overlap with a heapsegment; in this case, or when no overlap occurs, an emptyOptionalisreturned.- Parameters:
other- the segment to test for an overlap with this segment- Returns:
- a slice of this segment (where overlapping occurs)
fill
Fills the contents of this memory segment with the given value.More specifically, the given value is written into each address of thissegment. Equivalent to (but likely more efficient than) the following code:
But without any regard or guarantees on the ordering of particular memoryelements being set.for (long offset = 0; offset < segment.byteSize(); offset++) { segment.set(ValueLayout.JAVA_BYTE, offset, value);}This method can be useful to initialize or reset the contents of a memory segment.
- Parameters:
value- the value to write into this segment- Returns:
- this memory segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if this segment isread-only
copyFrom
Performs a bulk copy from the given source segment to this segment. More specifically,the bytes at offset0throughsrc.byteSize() - 1in the sourcesegment are copied into this segment at offset0throughsrc.byteSize() - 1.Calling this method is equivalent to the following code:
MemorySegment.copy(src, 0, this, 0, src.byteSize());- Parameters:
src- the source segment- Returns:
- this segment
- Throws:
IndexOutOfBoundsException- ifsrc.byteSize() > this.byteSize()IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalStateException- if thescope associated withsrcis notaliveWrongThreadException- if this method is called from a threadT, such thatsrc.isAccessibleBy(T) == falseIllegalArgumentException- if this segment isread-only
mismatch
Finds and returns the offset, in bytes, of the first mismatch betweenthis segment and the given other segment. The offset is relative to theaddress of each segment and will be in therange of 0 (inclusive) up to thesize (in bytes) ofthe smaller memory segment (exclusive).If the two segments share a common prefix then the returned offset isthe length of the common prefix, and it follows that there is a mismatchbetween the two segments at that offset within the respective segments.If one segment is a proper prefix of the other, then the returned offset isthe smallest of the segment sizes, and it follows that the offset is onlyvalid for the larger segment. Otherwise, there is no mismatch and
-1is returned.- Parameters:
other- the segment to be tested for a mismatch with this segment- Returns:
- the relative offset, in bytes, of the first mismatch between thisand the given other segment, otherwise -1 if no mismatch
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalStateException- if thescope associated withotheris notaliveWrongThreadException- if this method is called from a threadT, such thatother.isAccessibleBy(T) == false
isLoaded
boolean isLoaded()Determines whether all the contents of this mapped segment are resident in physicalmemory.A return value of
trueimplies that it is highly likelythat all the data in this segment is resident in physical memory andmay therefore be accessed without incurring any virtual-memory pagefaults or I/O operations. A return value offalsedoes notnecessarily imply that this segment's contents are not resident in physicalmemory.The returned value is a hint, rather than a guarantee, because theunderlying operating system may have paged out some of this segment's databy the time that an invocation of this method returns.
- Returns:
trueif it is likely that the contents of this segment are resident in physical memory- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseUnsupportedOperationException- if this segment is not a mapped memory segment, e.g. ifisMapped() == false
load
void load()Loads the contents of this mapped segment into physical memory.This method makes a best effort to ensure that, when it returns,the contents of this segment are resident in physical memory. Invoking thismethod may cause some number of page faults and I/O operations tooccur.
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseUnsupportedOperationException- if this segment is not a mapped memory segment, e.g. ifisMapped() == false
unload
void unload()Unloads the contents of this mapped segment from physical memory.This method makes a best effort to ensure that the contents of this segmentare no longer resident in physical memory. Accessing this segment's contentsafter invoking this method may cause some number of page faults and I/O operationsto occur (as this segment's contents might need to be paged back in).
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseUnsupportedOperationException- if this segment is not a mapped memory segment, e.g. ifisMapped() == false
force
void force()Forces any changes made to the contents of this mapped segment to be written tothe storage device described by the mapped segment's file descriptor.If the file descriptor associated with this mapped segment resides on a localstorage device then when this method returns it is guaranteed that all changesmade to this segment since it was created, or since this method was last invoked,will have been written to that device.
If the file descriptor associated with this mapped segment does not reside ona local device then no such guarantee is made.
If this segment was not mapped in read/write mode(
FileChannel.MapMode.READ_WRITE) then invoking thismethod may have no effect. In particular, the method has no effect for segmentsmapped in read-only or private mapping modes. This method may or may not have aneffect for implementation-specific mapping modes.- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseUnsupportedOperationException- if this segment is not a mapped memory segment, e.g. ifisMapped() == falseUncheckedIOException- if there is an I/O error writing the contents of this segment to the associated storage device
asByteBuffer
ByteBuffer asByteBuffer()Wraps this segment in aByteBuffer. Some properties of the returned bufferare linked to the properties of this segment. More specifically, the resultingbuffer has the following characteristics:- It isread-only, if this segment is aread-only segment;
- Itsposition is set to zero;
- Itscapacity andlimit are both set to this segment'ssize. For this reason, a byte buffer cannotbe returned if this segment's size is greater than
Integer.MAX_VALUE; - It is adirect buffer, if this is anative segment.
The life-cycle of the returned buffer is tied to that of this segment. That is,accessing the returned buffer after the scope associated with this segment is nolongeralive, will throw an
IllegalStateException. Similarly, accessing the returned buffer from athreadTsuch thatisAccessible(T) == falsewill throw aWrongThreadException.If this segment isaccessible from a singlethread, calling read/write I/O operations on the resulting buffer might result inunspecified exceptions being thrown. Examples of such problematic operations are
AsynchronousSocketChannel.read(ByteBuffer)andAsynchronousSocketChannel.write(ByteBuffer).Finally, the resulting buffer's byte order is
ByteOrder.BIG_ENDIAN; this can be changed usingByteBuffer.order(java.nio.ByteOrder).- Returns:
- a
ByteBufferview of this memory segment - Throws:
UnsupportedOperationException- if this segment cannot be mapped onto aByteBufferinstance, e.g. if it is a heap segment backed by an array other thanbyte[]), or if its size is greater thanInteger.MAX_VALUE
toArray
Copy the contents of this memory segment into a new byte array.- Parameters:
elementLayout- the source element layout. If the byte order associated with the layout is different from thenative order, a byte swap operation will be performed on each array element- Returns:
- a new byte array whose contents are copied from this memory segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalStateException- if this segment's contents cannot be copied into abyte[]instance, e.g. its size is greater thanInteger.MAX_VALUE
toArray
Copy the contents of this memory segment into a new short array.- Parameters:
elementLayout- the source element layout. If the byte order associated with the layout is different from thenative order, a byte swap operation will be performed on each array element- Returns:
- a new short array whose contents are copied from this memory segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalStateException- if this segment's contents cannot be copied into ashort[]instance, e.g. becausebyteSize() % 2 != 0, orbyteSize() / 2 > Integer.MAX_VALUE
toArray
Copy the contents of this memory segment into a new char array.- Parameters:
elementLayout- the source element layout. If the byte order associated with the layout is different from thenative order, a byte swap operation will be performed on each array element- Returns:
- a new char array whose contents are copied from this memory segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalStateException- if this segment's contents cannot be copied into achar[]instance, e.g. becausebyteSize() % 2 != 0, orbyteSize() / 2 > Integer.MAX_VALUE
toArray
Copy the contents of this memory segment into a new int array.- Parameters:
elementLayout- the source element layout. If the byte order associated with the layout is different from thenative order, a byte swap operation will be performed on each array element.- Returns:
- a new int array whose contents are copied from this memory segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalStateException- if this segment's contents cannot be copied into aint[]instance, e.g. becausebyteSize() % 4 != 0, orbyteSize() / 4 > Integer.MAX_VALUE
toArray
Copy the contents of this memory segment into a new float array.- Parameters:
elementLayout- the source element layout. If the byte order associated with the layout is different from thenative order, a byte swap operation will be performed on each array element- Returns:
- a new float array whose contents are copied from this memory segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalStateException- if this segment's contents cannot be copied into afloat[]instance, e.g. becausebyteSize() % 4 != 0, orbyteSize() / 4 > Integer.MAX_VALUE
toArray
Copy the contents of this memory segment into a new long array.- Parameters:
elementLayout- the source element layout. If the byte order associated with the layout is different from thenative order, a byte swap operation will be performed on each array element- Returns:
- a new long array whose contents are copied from this memory segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalStateException- if this segment's contents cannot be copied into along[]instance, e.g. becausebyteSize() % 8 != 0, orbyteSize() / 8 > Integer.MAX_VALUE
toArray
Copy the contents of this memory segment into a new double array.- Parameters:
elementLayout- the source element layout. If the byte order associated with the layout is different from thenative order, a byte swap operation will be performed on each array element- Returns:
- a new double array whose contents are copied from this memory segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalStateException- if this segment's contents cannot be copied into adouble[]instance, e.g. becausebyteSize() % 8 != 0, orbyteSize() / 8 > Integer.MAX_VALUE
getString
Reads a null-terminated string from this segment at the given offset, using theUTF-8 charset.Calling this method is equivalent to the following code:
getString(offset, StandardCharsets.UTF_8);- Parameters:
offset- the offset in bytes (relative to this segment address) at which this access operation will occur- Returns:
- a Java string constructed from the bytes read from the given starting address up to (but not including) the first
'\0'terminator character (assuming one is found) - Throws:
IllegalArgumentException- if the size of the string is greater than the largest string supported by the platformIndexOutOfBoundsException- ifoffset < 0IndexOutOfBoundsException- if no string terminator (e.g.'\0') is present in this segment between the givenoffsetand the end of this segment.IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == false
getString
Reads a null-terminated string from this segment at the given offset, using theprovided charset.This method always replaces malformed-input and unmappable-charactersequences with this charset's default replacement string. The
CharsetDecoderclass should be used when more controlover the decoding process is required.Getting a string from a segment with a known byte offset andknown byte length can be done like so:
byte[] bytes = new byte[length]; MemorySegment.copy(segment, JAVA_BYTE, offset, bytes, 0, length); return new String(bytes, charset);- Parameters:
offset- offset in bytes (relative to this segment address) at which this access operation will occurcharset- the charset used todecode the string bytes. Thecharsetmust be astandard charset- Returns:
- a Java string constructed from the bytes read from the given starting address up to (but not including) the first
'\0'terminator character (assuming one is found) - Throws:
IllegalArgumentException- if the size of the string is greater than the largest string supported by the platformIndexOutOfBoundsException- ifoffset < 0IndexOutOfBoundsException- if no string terminator (e.g.'\0') is present in this segment between the givenoffsetand the end of this segment. The byte size of the string terminator depends on the selectedcharset. For instance, this is 1 forStandardCharsets.US_ASCIIand 2 forStandardCharsets.UTF_16IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- ifcharsetis not astandard charset
setString
Writes the given string into this segment at the given offset, converting it to a null-terminated byte sequence using theUTF-8 charset.Calling this method is equivalent to the following code:
setString(offset, str, StandardCharsets.UTF_8);- Parameters:
offset- the offset in bytes (relative to this segment address) at which this access operation will occur, the final address of this write operation can be expressed asaddress() + offset.str- the Java string to be written into this segment- Throws:
IndexOutOfBoundsException- ifoffset < 0IndexOutOfBoundsException- ifoffset > byteSize() - (B + 1), whereBis the size, in bytes, of the string encoded using UTF-8 charsetstr.getBytes(StandardCharsets.UTF_8).length)IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if this segment isread-only
setString
Writes the given string into this segment at the given offset, converting it to anull-terminated byte sequence using the provided charset.This method always replaces malformed-input and unmappable-charactersequences with this charset's default replacement string. The
CharsetDecoderclass should be used when more controlover the decoding process is required.If the given string contains any
'\0'characters, they will becopied as well. This means that, depending on the method used to readthe string, such asgetString(long), the stringwill appear truncated when read again.- Parameters:
offset- offset in bytes (relative to this segment address) at which this access operation will occur, the final address of this write operation can be expressed asaddress() + offsetstr- the Java string to be written into this segmentcharset- the charset used toencode the string bytes. Thecharsetmust be astandard charset- Throws:
IndexOutOfBoundsException- ifoffset < 0IndexOutOfBoundsException- ifoffset > byteSize() - (B + N), where:Bis the size, in bytes, of the string encoded using the provided charset (e.g.str.getBytes(charset).length);Nis the size (in bytes) of the terminator char according to the provided charset. For instance, this is 1 forStandardCharsets.US_ASCIIand 2 forStandardCharsets.UTF_16.
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- ifcharsetis not astandard charsetIllegalArgumentException- if this segment isread-only
ofBuffer
Creates a memory segment that is backed by the same region of memory that backsthe givenBufferinstance. The segment starts relative to the buffer'sposition (inclusive) and ends relative to the buffer's limit (exclusive).If the buffer isread-only, the resulting segmentis alsoread-only. Moreover, if the bufferis adirect buffer, the returned segment is anative segment; otherwise, the returned memory segment is a heap segment.
If the provided buffer has been obtained by calling
asByteBuffer()on amemory segment whosescope isS, the returned segmentwill be associated with the same scopeS. Otherwise, the scope of thereturned segment is an automatic scope that keeps the provided buffer reachable.As such, if the provided buffer is a direct buffer, its backing memory region willnot be deallocated as long as the returned segment, or any of its slices, are keptreachable.- Parameters:
buffer- the buffer instance to be turned into a new memory segment- Returns:
- a memory segment, derived from the given buffer instance
- Throws:
IllegalArgumentException- if the providedbufferis a heap buffer but is not backed by an array; For example, buffers directly or indirectly obtained via (CharBuffer.wrap(CharSequence)orCharBuffer.wrap(char[], int, int)are not backed by an array.
ofArray
Creates a heap segment backed by the on-heap region of memory that holds the givenbyte array. The scope of the returned segment is an automatic scope that keepsthe given array reachable. The returned segment is always accessible, from anythread. Itsaddress()is set to zero.- Parameters:
byteArray- the primitive array backing the heap memory segment- Returns:
- a heap memory segment backed by a byte array
ofArray
Creates a heap segment backed by the on-heap region of memory that holds the givenchar array. The scope of the returned segment is an automatic scope that keepsthe given array reachable. The returned segment is always accessible, from anythread. Itsaddress()is set to zero.- Parameters:
charArray- the primitive array backing the heap segment- Returns:
- a heap memory segment backed by a char array
ofArray
Creates a heap segment backed by the on-heap region of memory that holds the givenshort array. The scope of the returned segment is an automatic scope that keepsthe given array reachable. The returned segment is always accessible, from anythread. Itsaddress()is set to zero.- Parameters:
shortArray- the primitive array backing the heap segment- Returns:
- a heap memory segment backed by a short array
ofArray
Creates a heap segment backed by the on-heap region of memory that holds the givenint array. The scope of the returned segment is an automatic scope that keepsthe given array reachable. The returned segment is always accessible, from anythread. Itsaddress()is set to zero.- Parameters:
intArray- the primitive array backing the heap segment- Returns:
- a heap memory segment backed by an int array
ofArray
Creates a heap segment backed by the on-heap region of memory that holds the givenfloat array. The scope of the returned segment is an automatic scope that keepsthe given array reachable. The returned segment is always accessible, from anythread. Itsaddress()is set to zero.- Parameters:
floatArray- the primitive array backing the heap segment- Returns:
- a heap memory segment backed by a float array
ofArray
Creates a heap segment backed by the on-heap region of memory that holds the givenlong array. The scope of the returned segment is an automatic scope that keepsthe given array reachable. The returned segment is always accessible, from anythread. Itsaddress()is set to zero.- Parameters:
longArray- the primitive array backing the heap segment- Returns:
- a heap memory segment backed by a long array
ofArray
Creates a heap segment backed by the on-heap region of memory that holds the givendouble array. The scope of the returned segment is an automatic scope that keepsthe given array reachable. The returned segment is always accessible, from anythread. Itsaddress()is set to zero.- Parameters:
doubleArray- the primitive array backing the heap segment- Returns:
- a heap memory segment backed by a double array
ofAddress
Creates a zero-length native segment from the givenaddress value.The returned segment is associated with the global scope and is accessible fromany thread.
On 32-bit platforms, the given address value will be normalized such that thehighest-order ("leftmost") 32 bits of the
addressof the returned memory segment are set to zero.- Parameters:
address- the address of the returned native segment- Returns:
- a zero-length native segment with the given address
copy
static void copy(MemorySegment srcSegment, long srcOffset,MemorySegment dstSegment, long dstOffset, long bytes) Performs a bulk copy from source segment to destination segment. Morespecifically, the bytes at offsetsrcOffsetthroughsrcOffset + bytes - 1in the source segment are copied into thedestination segment at offsetdstOffsetthroughdstOffset + bytes - 1.If the source segment overlaps with the destination segment, then the copying isperformed as if the bytes at offset
srcOffsetthroughsrcOffset + bytes - 1in the source segment were first copied into atemporary segment with sizebytes, and then the contents of the temporarysegment were copied into the destination segment at offsetdstOffsetthroughdstOffset + bytes - 1.The result of a bulk copy is unspecified if, in the uncommon case, the sourcesegment and the destination segment do not overlap, but refer to overlappingregions of the same backing storage using different addresses. For example, thismay occur if the same file ismapped to two segments.
Calling this method is equivalent to the following code:
MemorySegment.copy(srcSegment, ValueLayout.JAVA_BYTE, srcOffset, dstSegment, ValueLayout.JAVA_BYTE, dstOffset, bytes);- Parameters:
srcSegment- the source segmentsrcOffset- the starting offset, in bytes, of the source segmentdstSegment- the destination segmentdstOffset- the starting offset, in bytes, of the destination segmentbytes- the number of bytes to be copied- Throws:
IllegalStateException- if thescope associated withsrcSegmentis notaliveWrongThreadException- if this method is called from a threadT, such thatsrcSegment.isAccessibleBy(T) == falseIllegalStateException- if thescope associated withdstSegmentis notaliveWrongThreadException- if this method is called from a threadT, such thatdstSegment.isAccessibleBy(T) == falseIndexOutOfBoundsException- ifsrcOffset > srcSegment.byteSize() - bytesIndexOutOfBoundsException- ifdstOffset > dstSegment.byteSize() - bytesIndexOutOfBoundsException- if eithersrcOffset,dstOffsetorbytesare< 0IllegalArgumentException- ifdstSegmentisread-only
copy
static void copy(MemorySegment srcSegment,ValueLayout srcElementLayout, long srcOffset,MemorySegment dstSegment,ValueLayout dstElementLayout, long dstOffset, long elementCount) Performs a bulk copy from source segment to destination segment. Morespecifically, ifSis the byte size of the element layouts, the bytes atoffsetsrcOffsetthroughsrcOffset + (elementCount * S) - 1in the source segment are copied into the destination segment at offsetdstOffsetthroughdstOffset + (elementCount * S) - 1.The copy occurs in an element-wise fashion: the bytes in the source segment areinterpreted as a sequence of elements whose layout is
srcElementLayout,whereas the bytes in the destination segment are interpreted as a sequence ofelements whose layout isdstElementLayout. Both element layouts must havethe same sizeS. If the byte order of the two provided element layoutsdiffers, the bytes corresponding to each element to be copied are swappedaccordingly during the copy operation.If the source segment overlaps with the destination segment, then the copying isperformed as if the bytes at offset
srcOffsetthroughsrcOffset + (elementCount * S) - 1in the source segment were first copiedinto a temporary segment with sizebytes, and then the contents of thetemporary segment were copied into the destination segment at offsetdstOffsetthroughdstOffset + (elementCount * S) - 1.The result of a bulk copy is unspecified if, in the uncommon case, the sourcesegment and the destination segment do not overlap, but refer to overlappingregions of the same backing storage using different addresses. For example,this may occur if the same file ismapped to twosegments.
- Parameters:
srcSegment- the source segmentsrcElementLayout- the element layout associated with the source segmentsrcOffset- the starting offset, in bytes, of the source segmentdstSegment- the destination segmentdstElementLayout- the element layout associated with the destination segmentdstOffset- the starting offset, in bytes, of the destination segmentelementCount- the number of elements to be copied- Throws:
IllegalArgumentException- if the element layouts have different sizes, if the source (resp. destination) segment/offset areincompatible with the alignment constraint in the source (resp. destination) element layoutIllegalArgumentException- ifsrcElementLayout.byteAlignment() > srcElementLayout.byteSize()IllegalArgumentException- ifdstElementLayout.byteAlignment() > dstElementLayout.byteSize()IllegalStateException- if thescope associated withsrcSegmentis notaliveWrongThreadException- if this method is called from a threadT, such thatsrcSegment.isAccessibleBy(T) == falseIllegalStateException- if thescope associated withdstSegmentis notaliveWrongThreadException- if this method is called from a threadT, such thatdstSegment.isAccessibleBy(T) == falseIllegalArgumentException- ifdstSegmentisread-onlyIndexOutOfBoundsException- ifelementCount * srcLayout.byteSize()overflowsIndexOutOfBoundsException- ifelementCount * dtsLayout.byteSize()overflowsIndexOutOfBoundsException- ifsrcOffset > srcSegment.byteSize() - (elementCount * srcLayout.byteSize())IndexOutOfBoundsException- ifdstOffset > dstSegment.byteSize() - (elementCount * dstLayout.byteSize())IndexOutOfBoundsException- if eithersrcOffset,dstOffsetorelementCountare< 0
get
Reads a byte from this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be readoffset- the offset in bytes (relative to this segment address) at which this access operation will occur.- Returns:
- a byte value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0
set
Writes a byte into this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be writtenoffset- the offset in bytes (relative to this segment address) at which this access operation will occur.value- the byte value to be written.- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0IllegalArgumentException- if this segment isread-only
get
Reads a boolean from this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be readoffset- the offset in bytes (relative to this segment address) at which this access operation will occur- Returns:
- a boolean value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0
set
Writes a boolean into this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be writtenoffset- the offset in bytes (relative to this segment address) at which this access operation will occurvalue- the boolean value to be written- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0IllegalArgumentException- if this segment isread-only
get
Reads a char from this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be readoffset- the offset in bytes (relative to this segment address) at which this access operation will occur- Returns:
- a char value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0
set
Writes a char into this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be writtenoffset- the offset in bytes (relative to this segment address) at which this access operation will occur.value- the char value to be written- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0IllegalArgumentException- if this segment isread-only
get
Reads a short from this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be readoffset- the offset in bytes (relative to this segment address) at which this access operation will occur- Returns:
- a short value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0
set
Writes a short into this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be writtenoffset- the offset in bytes (relative to this segment address) at which this access operation will occur.value- the short value to be written- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0IllegalArgumentException- if this segment isread-only
get
Reads an int from this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be readoffset- the offset in bytes (relative to this segment address) at which this access operation will occur.- Returns:
- an int value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0
set
Writes an int into this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be writtenoffset- the offset in bytes (relative to this segment address) at which this access operation will occurvalue- the int value to be written- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0IllegalArgumentException- if this segment isread-only
get
Reads a float from this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be readoffset- the offset in bytes (relative to this segment address) at which this access operation will occur- Returns:
- a float value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0
set
Writes a float into this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be writtenoffset- the offset in bytes (relative to this segment address) at which this access operation will occurvalue- the float value to be written- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0IllegalArgumentException- if this segment isread-only
get
Reads a long from this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be readoffset- the offset in bytes (relative to this segment address) at which this access operation will occur.- Returns:
- a long value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0
set
Writes a long into this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be writtenoffset- the offset in bytes (relative to this segment address) at which this access operation will occur.value- the long value to be written.- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0IllegalArgumentException- if this segment isread-only
get
Reads a double from this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be readoffset- the offset in bytes (relative to this segment address) at which this access operation will occur- Returns:
- a double value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0
set
Writes a double into this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be writtenoffset- the offset in bytes (relative to this segment address) at which this access operation will occurvalue- the double value to be written- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0IllegalArgumentException- if this segment isread-only
get
Reads an address from this segment at the given offset, with the given layout.The read address is wrapped in a native segment, associated with the global scope.Under normal conditions, the size of the returned segment is0. However,if the provided address layout has atarget layoutT, then the sizeof the returned segment is set toT.byteSize().- Parameters:
layout- the layout of the region of memory to be readoffset- the offset in bytes (relative to this segment address) at which this access operation will occur- Returns:
- a native segment wrapping an address read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- if provided address layout has atarget layoutT, and the address of the returned segmentincompatible with the alignment constraint inTIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0
set
Writes an address into this segment at the given offset, with the given layout.- Parameters:
layout- the layout of the region of memory to be writtenoffset- the offset in bytes (relative to this segment address) at which this access operation will occur.value- the address value to be written.- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIndexOutOfBoundsException- ifoffset > byteSize() - layout.byteSize()oroffset < 0IllegalArgumentException- ifvalueis not anative segmentIllegalArgumentException- if this segment isread-only
getAtIndex
Reads a byte from this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be readindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).- Returns:
- a byte value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0
getAtIndex
Reads a boolean from this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be readindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).- Returns:
- a boolean value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0
getAtIndex
Reads a char from this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be readindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).- Returns:
- a char value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0
setAtIndex
Writes a char into this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be writtenindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).value- the char value to be written- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0IllegalArgumentException- if this segment isread-only
getAtIndex
Reads a short from this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be readindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).- Returns:
- a short value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0
setAtIndex
Writes a byte into this segment at the given index, scaled by the given layout size.- Parameters:
layout- the layout of the region of memory to be writtenindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).value- the short value to be written- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0IllegalArgumentException- if this segment isread-only
setAtIndex
Writes a boolean into this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be writtenindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).value- the short value to be written- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0IllegalArgumentException- if this segment isread-only
setAtIndex
Writes a short into this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be writtenindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).value- the short value to be written- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0IllegalArgumentException- if this segment isread-only
getAtIndex
Reads an int from this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be read.index- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).- Returns:
- an int value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0
setAtIndex
Writes an int into this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be writtenindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).value- the int value to be written- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0IllegalArgumentException- if this segment isread-only
getAtIndex
Reads a float from this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be readindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).- Returns:
- a float value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0
setAtIndex
Writes a float into this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be writtenindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).value- the float value to be written- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0IllegalArgumentException- if this segment isread-only
getAtIndex
Reads a long from this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be readindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).- Returns:
- a long value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0
setAtIndex
Writes a long into this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be writtenindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).value- the long value to be written- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0IllegalArgumentException- if this segment isread-only
getAtIndex
Reads a double from this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be readindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).- Returns:
- a double value read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0
setAtIndex
Writes a double into this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be writtenindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).value- the double value to be written- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layoutIllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0IllegalArgumentException- if this segment isread-only
getAtIndex
Reads an address from this segment at the given at the given index, scaled by thegiven layout size. The read address is wrapped in a native segment, associatedwith the global scope. Under normal conditions, the size of the returned segmentis0. However, if the provided address layout has atarget layoutT, then the sizeof the returned segment is set toT.byteSize().- Parameters:
layout- the layout of the region of memory to be readindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).- Returns:
- a native segment wrapping an address read from this segment
- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layout.IllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IllegalArgumentException- if provided address layout has atarget layoutT, and the address of the returned segment isincompatible with the alignment constraint inTIndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0
setAtIndex
Writes an address into this segment at the given index, scaled by the givenlayout size.- Parameters:
layout- the layout of the region of memory to be writtenindex- a logical index. The offset in bytes (relative to this segment address) at which the access operation will occur can be expressed as(index * layout.byteSize()).value- the address value to be written- Throws:
IllegalStateException- if thescope associated with this segment is notaliveWrongThreadException- if this method is called from a threadT, such thatisAccessibleBy(T) == falseIllegalArgumentException- if the access operation isincompatible with the alignment constraint in the provided layout.IllegalArgumentException- iflayout.byteAlignment() > layout.byteSize()IndexOutOfBoundsException- ifindex * layout.byteSize()overflowsIndexOutOfBoundsException- ifindex * layout.byteSize() > byteSize() - layout.byteSize()orindex < 0IllegalArgumentException- ifvalueis not anative segmentIllegalArgumentException- if this segment isread-only
equals
Compares the specified object with this memory segment for equality. Returnstrueif and only if the specified object is also a memory segment, and ifthe two segments refer to the same location, in some region of memory.More specifically, for two segments
s1ands2to be consideredequal, all the following must be true:s1.heapBase().equals(s2.heapBase()), that is, the two segments must be of the same kind; either both arenative segments, backed by off-heap memory, or both are backed by the same on-heapJava object;s1.address() == s2.address(), that is, the address of the two segments should be the same. This means that the two segments either refer to the same location in some off-heap region, or they refer to the same offset inside their associatedJava object.
- Overrides:
equalsin classObject- API Note:
- This method does not perform a structural comparison of the contents of the two memory segments. Clients can compare memory segments structurally by using the
mismatch(MemorySegment)method instead. Note that this method doesnot compare the temporal and spatial bounds of two segments. As such, it is suitable to check whether two segments have the same address. - Parameters:
that- the object to be compared for equality with this memory segment- Returns:
trueif the specified object is equal to this memory segment- See Also:
hashCode
copy
static void copy(MemorySegment srcSegment,ValueLayout srcLayout, long srcOffset,Object dstArray, int dstIndex, int elementCount) Copies a number of elements from a source memory segment to a destination array.The elements, whose size and alignment constraints are specified by the givenlayout, are read from the source segment, starting at the given offset(expressed in bytes), and are copied into the destination array, at thegiven index.Supported array types are :
byte[],char[],short[],int[],float[],long[]anddouble[].- Parameters:
srcSegment- the source segmentsrcLayout- the source element layout. If the byte order associated with the layout is different from thenative order, a byte swap operation will be performed on each array elementsrcOffset- the starting offset, in bytes, of the source segmentdstArray- the destination arraydstIndex- the starting index of the destination arrayelementCount- the number of array elements to be copied- Throws:
IllegalStateException- if thescope associated withsrcSegmentis notaliveWrongThreadException- if this method is called from a threadT, such thatsrcSegment.isAccessibleBy(T) == falseIllegalArgumentException- ifdstArrayis not an array, or if it is an array but whose type is not supportedIllegalArgumentException- if the destination array component type does not matchsrcLayout.carrier()IllegalArgumentException- ifoffsetisincompatible with the alignment constraint in the source element layoutIllegalArgumentException- ifsrcLayout.byteAlignment() > srcLayout.byteSize()IndexOutOfBoundsException- ifelementCount * srcLayout.byteSize()overflowsIndexOutOfBoundsException- ifsrcOffset > srcSegment.byteSize() - (elementCount * srcLayout.byteSize())IndexOutOfBoundsException- ifdstIndex > dstArray.length - elementCountIndexOutOfBoundsException- if eithersrcOffset,dstIndexorelementCountare< 0
copy
static void copy(Object srcArray, int srcIndex,MemorySegment dstSegment,ValueLayout dstLayout, long dstOffset, int elementCount) Copies a number of elements from a source array to a destination memory segment.The elements, whose size and alignment constraints are specified by the givenlayout, are read from the source array, starting at the given index, and arecopied into the destination segment, at the given offset (expressed in bytes).
Supported array types are
byte[],char[],short[],int[],float[],long[]anddouble[].- Parameters:
srcArray- the source arraysrcIndex- the starting index of the source arraydstSegment- the destination segmentdstLayout- the destination element layout. If the byte order associated with the layout is different from thenative order, a byte swap operation will be performed on each array element.dstOffset- the starting offset, in bytes, of the destination segmentelementCount- the number of array elements to be copied- Throws:
IllegalStateException- if thescope associated withdstSegmentis notaliveWrongThreadException- if this method is called from a threadT, such thatdstSegment.isAccessibleBy(T) == falseIllegalArgumentException- ifsrcArrayis not an array, or if it is an array but whose type is not supportedIllegalArgumentException- if the source array component type does not matchsrcLayout.carrier()IllegalArgumentException- ifoffsetisincompatible with the alignment constraint in the source element layoutIllegalArgumentException- ifdstLayout.byteAlignment() > dstLayout.byteSize()IllegalArgumentException- ifdstSegmentisread-onlyIndexOutOfBoundsException- ifelementCount * dstLayout.byteSize()overflowsIndexOutOfBoundsException- ifdstOffset > dstSegment.byteSize() - (elementCount * dstLayout.byteSize())IndexOutOfBoundsException- ifsrcIndex > srcArray.length - elementCountIndexOutOfBoundsException- if eithersrcIndex,dstOffsetorelementCountare< 0
mismatch
static long mismatch(MemorySegment srcSegment, long srcFromOffset, long srcToOffset,MemorySegment dstSegment, long dstFromOffset, long dstToOffset) Finds and returns the relative offset, in bytes, of the first mismatch between thesource and the destination segments. More specifically, the bytes at offsetsrcFromOffsetthroughsrcToOffset - 1in the source segment arecompared against the bytes at offsetdstFromOffsetthroughdstToOffset - 1in the destination segment.If the two segments, over the specified ranges, share a common prefix then thereturned offset is the length of the common prefix, and it follows that there is amismatch between the two segments at that relative offset within the respectivesegments. If one segment is a proper prefix of the other, over the specifiedranges, then the returned offset is the smallest range, and it follows that therelative offset is only valid for the segment with the larger range. Otherwise,there is no mismatch and
-1is returned.- Parameters:
srcSegment- the source segment.srcFromOffset- the offset (inclusive) of the first byte in the source segment to be testedsrcToOffset- the offset (exclusive) of the last byte in the source segment to be testeddstSegment- the destination segmentdstFromOffset- the offset (inclusive) of the first byte in the destination segment to be testeddstToOffset- the offset (exclusive) of the last byte in the destination segment to be tested- Returns:
- the relative offset, in bytes, of the first mismatch between the source and destination segments, otherwise -1 if no mismatch
- Throws:
IllegalStateException- if thescope associated withsrcSegmentis notaliveWrongThreadException- if this method is called from a threadT, such thatsrcSegment.isAccessibleBy(T) == falseIllegalStateException- if thescope associated withdstSegmentis notaliveWrongThreadException- if this method is called from a threadT, such thatdstSegment.isAccessibleBy(T) == falseIndexOutOfBoundsException- ifsrcFromOffset < 0,srcToOffset < srcFromOffsetorsrcToOffset > srcSegment.byteSize()IndexOutOfBoundsException- ifdstFromOffset < 0,dstToOffset < dstFromOffsetordstToOffset > dstSegment.byteSize()- See Also: