- All Superinterfaces:
Addressable
,AutoCloseable
close()
).
All implementations of this interface must be value-based;
programmers should treat instances that are equal as interchangeable and should not
use instances for synchronization, or unpredictable behavior may occur. For example, in a future release,
synchronization may fail. The equals
method should be used for comparisons.
Non-platform classes should not implement MemorySegment directly.
Unless otherwise specified, passing a null
argument, or an array argument containing one or more null
elements to a method in this class causes a NullPointerException
to be thrown.
Constructing memory segments
There are multiple ways to obtain a memory segment. First, memory segments backed by off-heap memory can be allocated using one of the many factory methods provided (seeallocateNative(MemoryLayout)
,
allocateNative(long)
and allocateNative(long, long)
). Memory segments obtained
in this way are called native memory segments.
It is also possible to obtain a memory segment backed by an existing heap-allocated Java array,
using one of the provided factory methods (e.g. ofArray(int[])
). Memory segments obtained
in this way are called array memory segments.
It is possible to obtain a memory segment backed by an existing Java byte buffer (see ByteBuffer
),
using the factory method ofByteBuffer(ByteBuffer)
.
Memory segments obtained in this way are called buffer memory segments. Note that buffer memory segments might
be backed by native memory (as in the case of native memory segments) or heap memory (as in the case of array memory segments),
depending on the characteristics of the byte buffer instance the segment is associated with. For instance, a buffer memory
segment obtained from a byte buffer created with the ByteBuffer.allocateDirect(int)
method will be backed
by native memory.
Finally, it is also possible to obtain a memory segment backed by a memory-mapped file using the factory method
mapFile(Path, long, long, FileChannel.MapMode)
. Such memory segments are called mapped memory segments;
mapped memory segments are associated with an underlying file descriptor. For more operations on mapped memory segments, please refer to the
MappedMemorySegments
class.
Array and buffer segments are effectively views over existing memory regions which might outlive the
lifecycle of the segments derived from them, and can even be manipulated directly (e.g. via array access, or direct use
of the ByteBuffer
API) by other clients. As a result, while sharing array or buffer segments is possible,
it is strongly advised that clients wishing to do so take extra precautions to make sure that the underlying memory sources
associated with such segments remain inaccessible, and that said memory sources are never aliased by more than one segment
at a time - e.g. so as to prevent concurrent modifications of the contents of an array, or buffer segment.
Explicit deallocation
Memory segments are closed explicitly (seeclose()
). When a segment is closed, it is no longer
alive (see isAlive()
, and subsequent operation on the segment (or on any MemoryAddress
instance
derived from it) will fail with IllegalStateException
.
Closing a segment might trigger the releasing of the underlying memory resources associated with said segment, depending on the kind of memory segment being considered:
- closing a native memory segment results in freeing the native memory associated with it
- closing a mapped memory segment results in the backing memory-mapped file to be unmapped
- closing a buffer, or a heap segment does not have any side-effect, other than marking the segment
as not alive (see
isAlive()
). Also, since the buffer and heap segments might keep strong references to the original buffer or array instance, it is the responsibility of clients to ensure that these segments are discarded in a timely manner, so as not to prevent garbage collection to reclaim the underlying objects.
Access modes
Memory segments supports zero or more access modes. Supported access modes areREAD
,
WRITE
, CLOSE
, SHARE
and HANDOFF
. The set of access modes supported by a segment alters the
set of operations that are supported by that segment. For instance, attempting to call close()
on
a segment which does not support the CLOSE
access mode will result in an exception.
The set of supported access modes can only be made stricter (by supporting fewer access modes). This means that restricting the set of access modes supported by a segment before sharing it with other clients is generally a good practice if the creator of the segment wants to retain some control over how the segment is going to be accessed.
Memory segment views
Memory segments support views. For instance, it is possible to alter the set of supported access modes, by creating an immutable view of a memory segment, as follows:It is also possible to create views whose spatial bounds are stricter than the ones of the original segment (seeMemorySegment segment = ... MemorySegment roSegment = segment.withAccessModes(segment.accessModes() & ~WRITE);
asSlice(long, long)
).
Temporal bounds of the original segment are inherited by the view; that is, closing a segment view, such as a sliced
view, will cause the original segment to be closed; as such special care must be taken when sharing views
between multiple clients. If a client want to protect itself against early closure of a segment by
another actor, it is the responsibility of that client to take protective measures, such as removing CLOSE
from the set of supported access modes, before sharing the view with another client.
To allow for interoperability with existing code, a byte buffer view can be obtained from a memory segment
(see asByteBuffer()
). This can be useful, for instance, for those clients that want to keep using the
ByteBuffer
API, but need to operate on large memory segments. Byte buffers obtained in such a way support
the same spatial and temporal access restrictions associated to the memory segment from which they originated.
Thread confinement
Memory segments support strong thread-confinement guarantees. Upon creation, they are assigned an owner thread, typically the thread which initiated the creation operation. After creation, only the owner thread will be allowed to directly manipulate the memory segment (e.g. close the memory segment) or access the underlying memory associated with the segment using a memory access var handle. Any attempt to perform such operations from a thread other than the owner thread will result in a runtime failure.
The handoff(Thread)
method can be used to change the thread-confinement properties of a memory segment.
This method is, like close()
, a terminal operation which marks the original segment as not alive
(see isAlive()
) and creates a new segment with the desired thread-confinement properties. Calling
handoff(Thread)
is only possible if the segment features the corresponding HANDOFF
access mode.
For instance, if a client wants to transfer ownership of a segment to another (known) thread, it can do so as follows:
By doing so, the original segment is marked as not alive, and a new segment is returned whose owner thread isMemorySegment segment = ... MemorySegment aSegment = segment.handoff(threadA);
threadA
; this allows, for instance, for two threads A
and B
to share
a segment in a controlled, cooperative and race-free fashion (also known as serial thread confinement).
Alternatively, the share()
method can be used to remove thread ownership altogether; this is only possible
if the segment features the corresponding SHARE
access mode. The following code shows how clients can
obtain a shared segment:
Again here, the original segment is marked as not alive, and a new shared segment is returned which features no owner thread (e.g.MemorySegment segment = ... MemorySegment sharedSegment = segment.share();
ownerThread()
returns null
). This might be useful when multiple threads need to process
the contents of the same memory segment concurrently (e.g. in the case of parallel processing). For instance, a client
might obtain a Spliterator
from a shared segment, which can then be used to slice the segment and allow multiple
threads to work in parallel on disjoint segment slices. The following code can be used to sum all int values in a memory segment in parallel:
Once shared, a segment can be claimed back by a given thread (again usingSequenceLayout SEQUENCE_LAYOUT = MemoryLayout.ofSequence(1024, MemoryLayouts.JAVA_INT); try (MemorySegment segment = MemorySegment.allocateNative(SEQUENCE_LAYOUT).share()) { VarHandle VH_int = SEQUENCE_LAYOUT.elementLayout().varHandle(int.class); int sum = StreamSupport.stream(segment.spliterator(SEQUENCE_LAYOUT), true) .mapToInt(s -> (int)VH_int.get(s.address())) .sum(); }
handoff(Thread)
); in fact, many threads
can attempt to gain ownership of the same segment, concurrently, and only one of them is guaranteed to succeed.
When using shared segments, clients should make sure that no other thread is accessing the segment while
the segment is being closed. If one or more threads attempts to access a segment concurrently while the
segment is being closed, an exception might occur on both the accessing and the closing threads. Clients should
refrain from attempting to close a segment repeatedly (e.g. keep calling close()
until no exception is thrown);
such exceptions should instead be seen as an indication that the client code is lacking appropriate synchronization between the threads
accessing/closing the segment.
Implicit deallocation
Clients can register a memory segment against aCleaner
, to make sure that underlying resources associated with
that segment will be released when the segment becomes unreachable, which can be useful to prevent native memory
leaks. This can be achieved using the registerCleaner(Cleaner)
method, as follows:
Here, the original segment is marked as not alive, and a new segment is returned (the owner thread of the returned segment set is set to that of the current thread, seeMemorySegment segment = ... MemorySegment gcSegment = segment.registerCleaner(cleaner);
ownerThread()
); the new segment
will also be registered with the the Cleaner
instance provided to the registerCleaner(Cleaner)
method;
as such, if not closed explicitly (see close()
), the new segment will be automatically closed by the cleaner.- API Note:
- In the future, if the Java language permits,
MemorySegment
may become asealed
interface, which would prohibit subclassing except by other explicitly permitted subtypes. - Implementation Requirements:
- Implementations of this interface are immutable, thread-safe and value-based.
-
Field Summary
Modifier and TypeFieldDescriptionstatic int
Default access mode; this is a union of all the access modes supported by memory segments.static int
Close access mode; callingclose()
is supported by a segment which supports this access mode.static int
Handoff access mode; this segment support serial thread-confinement via thread ownership changes (seehandoff(NativeScope)
andhandoff(Thread)
).static int
Read access mode; read operations are supported by a segment which supports this access mode.static int
Share access mode; this segment support sharing with threads other than the owner thread (seeshare()
).static int
Write access mode; write operations are supported by a segment which supports this access mode. -
Method Summary
Modifier and TypeMethodDescriptionint
address()
The base memory address associated with this memory segment.static MemorySegment
allocateNative(long bytesSize)
Creates a new confined native memory segment that models a newly allocated block of off-heap memory with given size (in bytes).static MemorySegment
allocateNative(long bytesSize, long alignmentBytes)
Creates a new confined native memory segment that models a newly allocated block of off-heap memory with given size and alignment constraint (in bytes).static MemorySegment
allocateNative(MemoryLayout layout)
Creates a new confined native memory segment that models a newly allocated block of off-heap memory with given layout.Wraps this segment in aByteBuffer
.default MemorySegment
asSlice(long offset)
Obtains a new memory segment view whose base address is the same as the base address of this segment plus a given offset, and whose new size is computed by subtracting the specified offset from this segment size.asSlice(long offset, long newSize)
Obtains a new memory segment view whose base address is the same as the base address of this segment plus a given offset, and whose new size is specified by the given argument.default MemorySegment
asSlice(MemoryAddress newBase)
Obtains a new memory segment view whose base address is the given address, and whose new size is computed by subtracting the address offset relative to this segment (seeMemoryAddress.segmentOffset(MemorySegment)
) from this segment size.default MemorySegment
asSlice(MemoryAddress newBase, long newSize)
Obtains a new memory segment view whose base address is the given address, and whose new size is specified by the given argument.long
byteSize()
The size (in bytes) of this memory segment.void
close()
Closes this memory segment.void
copyFrom(MemorySegment src)
Performs a bulk copy from given source segment to this segment.fill(byte value)
Fills a value into this memory segment.Obtains a new confined memory segment backed by the same underlying memory region as this segment.handoff(NativeScope nativeScope)
Obtains a new confined memory segment backed by the same underlying memory region as this segment, but whose temporal bounds are controlled by the providedNativeScope
instance.boolean
hasAccessModes(int accessModes)
Does this segment support a given set of access modes?boolean
isAlive()
Is this segment alive?boolean
isMapped()
Is this a mapped segment?static MemorySegment
mapFile(Path path, long bytesOffset, long bytesSize, FileChannel.MapMode mapMode)
Creates a new confined mapped memory segment that models a memory-mapped region of a file from a given path.long
mismatch(MemorySegment other)
Finds and returns the offset, in bytes, of the first mismatch between this segment and a given other segment.static MemorySegment
ofArray(byte[] arr)
Creates a new confined array memory segment that models the memory associated with a given heap-allocated byte array.static MemorySegment
ofArray(char[] arr)
Creates a new confined array memory segment that models the memory associated with a given heap-allocated char array.static MemorySegment
ofArray(double[] arr)
Creates a new confined array memory segment that models the memory associated with a given heap-allocated double array.static MemorySegment
ofArray(float[] arr)
Creates a new confined array memory segment that models the memory associated with a given heap-allocated float array.static MemorySegment
ofArray(int[] arr)
Creates a new confined array memory segment that models the memory associated with a given heap-allocated int array.static MemorySegment
ofArray(long[] arr)
Creates a new confined array memory segment that models the memory associated with a given heap-allocated long array.static MemorySegment
ofArray(short[] arr)
Creates a new confined array memory segment that models the memory associated with a given heap-allocated short array.static MemorySegment
ofByteBuffer(ByteBuffer bb)
Creates a new confined buffer memory segment that models the memory associated with the given byte buffer.static MemorySegment
Returns a shared native memory segment whose base address isMemoryAddress.NULL
and whose size isLong.MAX_VALUE
.The thread owning this segment.registerCleaner(Cleaner cleaner)
Register this memory segment instance against aCleaner
object, by returning a new memory segment backed by the same underlying memory region as this segment.share()
Obtains a new shared memory segment backed by the same underlying memory region as this segment.spliterator(SequenceLayout layout)
Returns a spliterator for this memory segment.byte[]
Copy the contents of this memory segment into a fresh byte array.char[]
Copy the contents of this memory segment into a fresh char array.double[]
Copy the contents of this memory segment into a fresh double array.float[]
Copy the contents of this memory segment into a fresh float array.int[]
Copy the contents of this memory segment into a fresh int array.long[]
Copy the contents of this memory segment into a fresh long array.short[]
Copy the contents of this memory segment into a fresh short array.withAccessModes(int accessModes)
Obtains a segment view with specific access modes.
-
Field Details
-
READ
static final int READRead access mode; read operations are supported by a segment which supports this access mode.- See Also:
accessModes()
,withAccessModes(int)
, Constant Field Values
-
WRITE
static final int WRITEWrite access mode; write operations are supported by a segment which supports this access mode.- See Also:
accessModes()
,withAccessModes(int)
, Constant Field Values
-
CLOSE
static final int CLOSEClose access mode; callingclose()
is supported by a segment which supports this access mode.- See Also:
accessModes()
,withAccessModes(int)
, Constant Field Values
-
SHARE
static final int SHAREShare access mode; this segment support sharing with threads other than the owner thread (seeshare()
).- See Also:
accessModes()
,withAccessModes(int)
, Constant Field Values
-
HANDOFF
static final int HANDOFFHandoff access mode; this segment support serial thread-confinement via thread ownership changes (seehandoff(NativeScope)
andhandoff(Thread)
).- See Also:
accessModes()
,withAccessModes(int)
, Constant Field Values
-
ALL_ACCESS
static final int ALL_ACCESSDefault access mode; this is a union of all the access modes supported by memory segments.- See Also:
accessModes()
,withAccessModes(int)
, Constant Field Values
-
-
Method Details
-
address
MemoryAddress address()The base memory address associated with this memory segment. The returned address is a checked memory address and can therefore be used in dereference operations (seeMemoryAddress
).- Specified by:
address
in interfaceAddressable
- Returns:
- The base memory address.
- Throws:
IllegalStateException
- if this segment is not alive, or if access occurs from a thread other than the thread owning this segment
-
spliterator
Returns a spliterator for this memory segment. The returned spliterator reportsSpliterator.SIZED
,Spliterator.SUBSIZED
,Spliterator.IMMUTABLE
,Spliterator.NONNULL
andSpliterator.ORDERED
characteristics.The returned spliterator splits this segment according to the specified sequence layout; that is, if the supplied layout is a sequence layout whose element count is
N
, then callingSpliterator.trySplit()
will result in a spliterator serving approximativelyN/2
elements (depending on whether N is even or not). As such, splitting is possible as long asN >= 2
. The spliterator returns segments that feature the same access modes as the given segment less theCLOSE
access mode.The returned spliterator effectively allows to slice this segment into disjoint sub-segments, which can then be processed in parallel by multiple threads (if the segment is shared).
- Parameters:
layout
- the layout to be used for splitting.- Returns:
- the element spliterator for this segment
- Throws:
IllegalStateException
- if the segment is not alive, or if access occurs from a thread other than the thread owning this segment
-
ownerThread
Thread ownerThread()The thread owning this segment.- Returns:
- the thread owning this segment.
-
byteSize
long byteSize()The size (in bytes) of this memory segment.- Returns:
- The size (in bytes) of this memory segment.
-
withAccessModes
Obtains a segment view with specific access modes. Supported access modes areREAD
,WRITE
,CLOSE
,SHARE
andHANDOFF
. It is generally not possible to go from a segment with stricter access modes to one with less strict access modes. For instance, attempting to addWRITE
access mode to a read-only segment will be met with an exception.- Parameters:
accessModes
- an ORed mask of zero or more access modes.- Returns:
- a segment view with specific access modes.
- Throws:
IllegalArgumentException
- whenmask
is an access mask which is less strict than the one supported by this segment, or whenmask
contains bits not associated with any of the supported access modes.
-
hasAccessModes
boolean hasAccessModes(int accessModes)Does this segment support a given set of access modes?- Parameters:
accessModes
- an ORed mask of zero or more access modes.- Returns:
- true, if the access modes in
accessModes
are stricter than the ones supported by this segment. - Throws:
IllegalArgumentException
- whenmask
contains bits not associated with any of the supported access modes.
-
accessModes
int accessModes()Returns the access modes associated with this segment; the result is represented as ORed values fromREAD
,WRITE
,CLOSE
,SHARE
andHANDOFF
.- Returns:
- the access modes associated with this segment.
-
asSlice
Obtains a new memory segment view whose base address is the same as the base address of this segment plus a given offset, and whose new size is specified by the given argument.- Parameters:
offset
- The new segment base offset (relative to the current segment base address), specified in bytes.newSize
- The new segment size, specified in bytes.- Returns:
- a new memory segment view with updated base/limit addresses.
- Throws:
IndexOutOfBoundsException
- ifoffset < 0
,offset > byteSize()
,newSize < 0
, ornewSize > byteSize() - offset
- See Also:
asSlice(long)
,asSlice(MemoryAddress)
,asSlice(MemoryAddress, long)
-
asSlice
Obtains a new memory segment view whose base address is the given address, and whose new size is specified by the given argument.Equivalent to the following code:
asSlice(newBase.segmentOffset(this), newSize);
- Parameters:
newBase
- The new segment base address.newSize
- The new segment size, specified in bytes.- Returns:
- a new memory segment view with updated base/limit addresses.
- Throws:
IndexOutOfBoundsException
- ifoffset < 0
,offset > byteSize()
,newSize < 0
, ornewSize > byteSize() - offset
- See Also:
asSlice(long)
,asSlice(MemoryAddress)
,asSlice(long, long)
-
asSlice
Obtains a new memory segment view whose base address is the same as the base address of this segment plus a given offset, and whose new size is computed by subtracting the specified offset from this segment size.Equivalent to the following code:
asSlice(offset, byteSize() - offset);
- Parameters:
offset
- The new segment base offset (relative to the current segment base address), specified in bytes.- Returns:
- a new memory segment view with updated base/limit addresses.
- Throws:
IndexOutOfBoundsException
- ifoffset < 0
, oroffset > byteSize()
.- See Also:
asSlice(MemoryAddress)
,asSlice(MemoryAddress, long)
,asSlice(long, long)
-
asSlice
Obtains a new memory segment view whose base address is the given address, and whose new size is computed by subtracting the address offset relative to this segment (seeMemoryAddress.segmentOffset(MemorySegment)
) from this segment size.Equivalent to the following code:
asSlice(newBase.segmentOffset(this));
- Parameters:
newBase
- The new segment base offset (relative to the current segment base address), specified in bytes.- Returns:
- a new memory segment view with updated base/limit addresses.
- Throws:
IndexOutOfBoundsException
- ifaddress.segmentOffset(this) < 0
, oraddress.segmentOffset(this) > byteSize()
.- See Also:
asSlice(long)
,asSlice(MemoryAddress, long)
,asSlice(long, long)
-
isMapped
boolean isMapped()Is this a mapped segment? Returns true if this segment is a mapped memory segment, created using themapFile(Path, long, long, FileChannel.MapMode)
factory, or a buffer segment derived from aMappedByteBuffer
using theofByteBuffer(ByteBuffer)
factory.- Returns:
true
if this segment is a mapped segment.
-
isAlive
boolean isAlive()Is this segment alive?- Returns:
- true, if the segment is alive.
- See Also:
close()
-
close
void close()Closes this memory segment. This is a terminal operation; as a side-effect, if this operation completes without exceptions, this segment will be marked as not alive, and subsequent operations on this segment will fail withIllegalStateException
.Depending on the kind of memory segment being closed, calling this method further triggers deallocation of all the resources associated with the memory segment.
- Specified by:
close
in interfaceAutoCloseable
- API Note:
- This operation is not idempotent; that is, closing an already closed segment always results in an
exception being thrown. This reflects a deliberate design choice: segment state transitions should be
manifest in the client code; a failure in any of these transitions reveals a bug in the underlying application
logic. This is especially useful when reasoning about the lifecycle of dependent segment views (see
asSlice(MemoryAddress)
, where closing one segment might side-effect multiple segments. In such cases it might in fact not be obvious, looking at the code, as to whether a given segment is alive or not. - Throws:
IllegalStateException
- if this segment is not alive, or if access occurs from a thread other than the thread owning this segment, or if this segment is shared and the segment is concurrently accessed while this method is called.UnsupportedOperationException
- if this segment does not support theCLOSE
access mode.
-
handoff
Obtains a new confined memory segment backed by the same underlying memory region as this segment. The returned segment will be confined on the specified thread, and will feature the same spatial bounds and access modes (seeaccessModes()
) as this segment.This is a terminal operation; as a side-effect, if this operation completes without exceptions, this segment will be marked as not alive, and subsequent operations on this segment will fail with
IllegalStateException
.In case where the owner thread of the returned segment differs from that of this segment, write accesses to this segment's content happens-before hand-over from the current owner thread to the new owner thread, which in turn happens before read accesses to the returned segment's contents on the new owner thread.
- Parameters:
thread
- the new owner thread- Returns:
- a new confined memory segment whose owner thread is set to
thread
. - Throws:
IllegalStateException
- if this segment is not alive, or if access occurs from a thread other than the thread owning this segment.UnsupportedOperationException
- if this segment does not support theHANDOFF
access mode.
-
handoff
Obtains a new confined memory segment backed by the same underlying memory region as this segment, but whose temporal bounds are controlled by the providedNativeScope
instance.This is a terminal operation; as a side-effect, this segment will be marked as not alive, and subsequent operations on this segment will fail with
IllegalStateException
.The returned segment will feature only
READ
andWRITE
access modes (assuming these were available in the original segment). As such the returned segment cannot be closed directly usingclose()
- but it will be closed indirectly when this native scope is closed. The returned segment will also be confined by the same thread as the provided native scope (seeNativeScope.ownerThread()
).In case where the owner thread of the returned segment differs from that of this segment, write accesses to this segment's content happens-before hand-over from the current owner thread to the new owner thread, which in turn happens before read accesses to the returned segment's contents on the new owner thread.
- Parameters:
nativeScope
- the native scope.- Returns:
- a new confined memory segment backed by the same underlying memory region as this segment, but whose life-cycle
is tied to that of
nativeScope
. - Throws:
IllegalStateException
- if this segment is not alive, or if access occurs from a thread other than the thread owning this segment.UnsupportedOperationException
- if this segment does not support theHANDOFF
access mode.
-
registerCleaner
Register this memory segment instance against aCleaner
object, by returning a new memory segment backed by the same underlying memory region as this segment. The returned segment will feature the same confinement, spatial bounds and access modes (seeaccessModes()
) as this segment. Moreover, the returned segment will be associated with the specifiedCleaner
object; this allows for the segment to be closed as soon as it becomes unreachable, which might be helpful in preventing native memory leaks.This is a terminal operation; as a side-effect, if this operation completes without exceptions, this segment will be marked as not alive, and subsequent operations on this segment will fail with
IllegalStateException
.The implicit deallocation behavior associated with the returned segment will be preserved under terminal operations such as
handoff(Thread)
andshare()
.- Parameters:
cleaner
- the cleaner object, responsible for implicit deallocation of the returned segment.- Returns:
- a new memory segment backed by the same underlying memory region as this segment, which features implicit deallocation.
- Throws:
IllegalStateException
- if this segment is not alive, or if access occurs from a thread other than the thread owning this segment, or if this segment is already associated with a cleaner.UnsupportedOperationException
- if this segment does not support theCLOSE
access mode.
-
fill
Fills a value into this memory segment.More specifically, the given value is filled into each address of this segment. Equivalent to (but likely more efficient than) the following code:
without any regard or guarantees on the ordering of particular memory elements being set.byteHandle = MemoryLayout.ofSequence(MemoryLayouts.JAVA_BYTE) .varHandle(byte.class, MemoryLayout.PathElement.sequenceElement()); for (long l = 0; l < segment.byteSize(); l++) { byteHandle.set(segment.address(), l, value); }
Fill can be useful to initialize or reset the memory of a segment.
- Parameters:
value
- the value to fill into this segment- Returns:
- this memory segment
- Throws:
IllegalStateException
- if this segment is not alive, or if access occurs from a thread other than the thread owning this segmentUnsupportedOperationException
- if this segment does not support theWRITE
access mode
-
copyFrom
Performs a bulk copy from given source segment to this segment. More specifically, the bytes at offset0
throughsrc.byteSize() - 1
in the source segment are copied into this segment at offset0
throughsrc.byteSize() - 1
. If the source segment overlaps with this segment, then the copying is performed as if the bytes at offset0
throughsrc.byteSize() - 1
in the source segment were first copied into a temporary segment with sizebytes
, and then the contents of the temporary segment were copied into this segment at offset0
throughsrc.byteSize() - 1
.The result of a bulk copy is unspecified if, in the uncommon case, the source segment and this segment do not overlap, but refer to overlapping regions of the same backing storage using different addresses. For example, this may occur if the same file is
mapped
to two segments.- Parameters:
src
- the source segment.- Throws:
IndexOutOfBoundsException
- ifsrc.byteSize() > this.byteSize()
.IllegalStateException
- if either the source segment or this segment have been already closed, or if access occurs from a thread other than the thread owning either segment.UnsupportedOperationException
- if either the source segment or this segment do not feature required access modes; more specifically,src
should feature at least theREAD
access mode, while this segment should feature at least theWRITE
access mode.
-
mismatch
Finds and returns the offset, in bytes, of the first mismatch between this segment and a given other segment. The offset is relative to thebase address
of each segment and will be in the range of 0 (inclusive) up to thesize
(in bytes) of the smaller memory segment (exclusive).If the two segments share a common prefix then the returned offset is the length of the common prefix and it follows that there is a mismatch between the two segments at that offset within the respective segments. If one segment is a proper prefix of the other then the returned offset is the smaller of the segment sizes, and it follows that the offset is only valid for the larger segment. Otherwise, there is no mismatch and
-1
is 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 this and the given other segment, otherwise -1 if no mismatch
- Throws:
IllegalStateException
- if either this segment of the other segment have been already closed, or if access occurs from a thread other than the thread owning either segmentUnsupportedOperationException
- if either this segment or the other segment does not feature at least theREAD
access mode
-
asByteBuffer
ByteBuffer asByteBuffer()Wraps this segment in aByteBuffer
. Some of the properties of the returned buffer are linked to the properties of this segment. For instance, if this segment is immutable (e.g. the segment has access modeREAD
but notWRITE
), then the resulting buffer is read-only (seeBuffer.isReadOnly()
. Additionally, if this is a native memory segment, the resulting buffer is direct (seeByteBuffer.isDirect()
).The returned buffer's position (see
Buffer.position()
is initially set to zero, while the returned buffer's capacity and limit (seeBuffer.capacity()
andBuffer.limit()
, respectively) are set to this segment' size (seebyteSize()
). For this reason, a byte buffer cannot be returned if this segment' size is greater thanInteger.MAX_VALUE
.The life-cycle of the returned buffer will be tied to that of this segment. That means that if the this segment is closed (see
close()
, accessing the returned buffer will throw anIllegalStateException
.If this segment is shared, calling certain I/O operations on the resulting buffer might result in an unspecified exception being thrown. Examples of such problematic operations are
FileChannel.read(ByteBuffer)
,FileChannel.write(ByteBuffer)
,SocketChannel.read(ByteBuffer)
andSocketChannel.write(ByteBuffer)
.Finally, the resulting buffer's byte order is
ByteOrder.BIG_ENDIAN
; this can be changed usingByteBuffer.order(java.nio.ByteOrder)
.- Returns:
- a
ByteBuffer
view of this memory segment. - Throws:
UnsupportedOperationException
- if this segment cannot be mapped onto aByteBuffer
instance, e.g. because it models an heap-based segment that is not based on abyte[]
), or if its size is greater thanInteger.MAX_VALUE
, or if the segment does not support theREAD
access mode.
-
toByteArray
byte[] toByteArray()Copy the contents of this memory segment into a fresh byte array.- Returns:
- a fresh byte array copy of this memory segment.
- Throws:
UnsupportedOperationException
- if this segment does not feature theREAD
access mode, or if this segment's contents cannot be copied into abyte
instance, e.g. its size is greater thanInteger.MAX_VALUE
,IllegalStateException
- if this segment has been closed, or if access occurs from a thread other than the thread owning this segment.
-
toShortArray
short[] toShortArray()Copy the contents of this memory segment into a fresh short array.- Returns:
- a fresh short array copy of this memory segment.
- Throws:
UnsupportedOperationException
- if this segment does not feature theREAD
access mode, or if this segment's contents cannot be copied into ashort
instance, e.g. becausebyteSize() % 2 != 0
, orbyteSize() / 2 > Integer#MAX_VALUE
.IllegalStateException
- if this segment has been closed, or if access occurs from a thread other than the thread owning this segment.
-
toCharArray
char[] toCharArray()Copy the contents of this memory segment into a fresh char array.- Returns:
- a fresh char array copy of this memory segment.
- Throws:
UnsupportedOperationException
- if this segment does not feature theREAD
access mode, or if this segment's contents cannot be copied into achar
instance, e.g. becausebyteSize() % 2 != 0
, orbyteSize() / 2 > Integer#MAX_VALUE
.IllegalStateException
- if this segment has been closed, or if access occurs from a thread other than the thread owning this segment.
-
toIntArray
int[] toIntArray()Copy the contents of this memory segment into a fresh int array.- Returns:
- a fresh int array copy of this memory segment.
- Throws:
UnsupportedOperationException
- if this segment does not feature theREAD
access mode, or if this segment's contents cannot be copied into aint
instance, e.g. becausebyteSize() % 4 != 0
, orbyteSize() / 4 > Integer#MAX_VALUE
.IllegalStateException
- if this segment has been closed, or if access occurs from a thread other than the thread owning this segment.
-
toFloatArray
float[] toFloatArray()Copy the contents of this memory segment into a fresh float array.- Returns:
- a fresh float array copy of this memory segment.
- Throws:
UnsupportedOperationException
- if this segment does not feature theREAD
access mode, or if this segment's contents cannot be copied into afloat
instance, e.g. becausebyteSize() % 4 != 0
, orbyteSize() / 4 > Integer#MAX_VALUE
.IllegalStateException
- if this segment has been closed, or if access occurs from a thread other than the thread owning this segment.
-
toLongArray
long[] toLongArray()Copy the contents of this memory segment into a fresh long array.- Returns:
- a fresh long array copy of this memory segment.
- Throws:
UnsupportedOperationException
- if this segment does not feature theREAD
access mode, or if this segment's contents cannot be copied into along
instance, e.g. becausebyteSize() % 8 != 0
, orbyteSize() / 8 > Integer#MAX_VALUE
.IllegalStateException
- if this segment has been closed, or if access occurs from a thread other than the thread owning this segment.
-
toDoubleArray
double[] toDoubleArray()Copy the contents of this memory segment into a fresh double array.- Returns:
- a fresh double array copy of this memory segment.
- Throws:
UnsupportedOperationException
- if this segment does not feature theREAD
access mode, or if this segment's contents cannot be copied into adouble
instance, e.g. becausebyteSize() % 8 != 0
, orbyteSize() / 8 > Integer#MAX_VALUE
.IllegalStateException
- if this segment has been closed, or if access occurs from a thread other than the thread owning this segment.
-
ofByteBuffer
Creates a new confined buffer memory segment that models the memory associated with the given byte buffer. The segment starts relative to the buffer's position (inclusive) and ends relative to the buffer's limit (exclusive).The segment will feature all access modes (see
ALL_ACCESS
), unless the given buffer is read-only in which case the segment will not feature theWRITE
access mode, and its confinement thread is the current thread (seeThread.currentThread()
).The resulting memory segment keeps a reference to the backing buffer, to ensure it remains reachable for the life-time of the segment.
- Parameters:
bb
- the byte buffer backing the buffer memory segment.- Returns:
- a new confined buffer memory segment.
-
ofArray
Creates a new confined array memory segment that models the memory associated with a given heap-allocated byte array.The resulting memory segment keeps a reference to the backing array, to ensure it remains reachable for the life-time of the segment. The segment will feature all access modes (see
ALL_ACCESS
), and its confinement thread is the current thread (seeThread.currentThread()
).- Parameters:
arr
- the primitive array backing the array memory segment.- Returns:
- a new confined array memory segment.
-
ofArray
Creates a new confined array memory segment that models the memory associated with a given heap-allocated char array.The resulting memory segment keeps a reference to the backing array, to ensure it remains reachable for the life-time of the segment. The segment will feature all access modes (see
ALL_ACCESS
), and its confinement thread is the current thread (seeThread.currentThread()
).- Parameters:
arr
- the primitive array backing the array memory segment.- Returns:
- a new confined array memory segment.
-
ofArray
Creates a new confined array memory segment that models the memory associated with a given heap-allocated short array.The resulting memory segment keeps a reference to the backing array, to ensure it remains reachable for the life-time of the segment. The segment will feature all access modes (see
ALL_ACCESS
), and its confinement thread is the current thread (seeThread.currentThread()
).- Parameters:
arr
- the primitive array backing the array memory segment.- Returns:
- a new confined array memory segment.
-
ofArray
Creates a new confined array memory segment that models the memory associated with a given heap-allocated int array.The resulting memory segment keeps a reference to the backing array, to ensure it remains reachable for the life-time of the segment. The segment will feature all access modes (see
ALL_ACCESS
), and its confinement thread is the current thread (seeThread.currentThread()
).- Parameters:
arr
- the primitive array backing the array memory segment.- Returns:
- a new confined array memory segment.
-
ofArray
Creates a new confined array memory segment that models the memory associated with a given heap-allocated float array.The resulting memory segment keeps a reference to the backing array, to ensure it remains reachable for the life-time of the segment. The segment will feature all access modes (see
ALL_ACCESS
), and its confinement thread is the current thread (seeThread.currentThread()
).- Parameters:
arr
- the primitive array backing the array memory segment.- Returns:
- a new confined array memory segment.
-
ofArray
Creates a new confined array memory segment that models the memory associated with a given heap-allocated long array.The resulting memory segment keeps a reference to the backing array, to ensure it remains reachable for the life-time of the segment. The segment will feature all access modes (see
ALL_ACCESS
), and its confinement thread is the current thread (seeThread.currentThread()
).- Parameters:
arr
- the primitive array backing the array memory segment.- Returns:
- a new confined array memory segment.
-
ofArray
Creates a new confined array memory segment that models the memory associated with a given heap-allocated double array.The resulting memory segment keeps a reference to the backing array, to ensure it remains reachable for the life-time of the segment. The segment will feature all access modes (see
ALL_ACCESS
).- Parameters:
arr
- the primitive array backing the array memory segment.- Returns:
- a new confined array memory segment.
-
allocateNative
Creates a new confined native memory segment that models a newly allocated block of off-heap memory with given layout.This is equivalent to the following code:
allocateNative(layout.bytesSize(), layout.bytesAlignment());
- Implementation Note:
- The block of off-heap memory associated with the returned native memory segment is initialized to zero.
Moreover, a client is responsible to call the
close()
on a native memory segment, to make sure the backing off-heap memory block is deallocated accordingly. Failure to do so will result in off-heap memory leaks. - Parameters:
layout
- the layout of the off-heap memory block backing the native memory segment.- Returns:
- a new native memory segment.
- Throws:
IllegalArgumentException
- if the specified layout has illegal size or alignment constraint.
-
allocateNative
Creates a new confined native memory segment that models a newly allocated block of off-heap memory with given size (in bytes).This is equivalent to the following code:
allocateNative(bytesSize, 1);
- Implementation Note:
- The block of off-heap memory associated with the returned native memory segment is initialized to zero.
Moreover, a client is responsible to call the
close()
on a native memory segment, to make sure the backing off-heap memory block is deallocated accordingly. Failure to do so will result in off-heap memory leaks. - Parameters:
bytesSize
- the size (in bytes) of the off-heap memory block backing the native memory segment.- Returns:
- a new confined native memory segment.
- Throws:
IllegalArgumentException
- ifbytesSize < 0
.
-
mapFile
static MemorySegment mapFile(Path path, long bytesOffset, long bytesSize, FileChannel.MapMode mapMode) throws IOExceptionCreates a new confined mapped memory segment that models a memory-mapped region of a file from a given path.The segment will feature all access modes (see
ALL_ACCESS
), unless the given mapping mode is READ_ONLY, in which case the segment will not feature theWRITE
access mode, and its confinement thread is the current thread (seeThread.currentThread()
).The content of a mapped memory segment can change at any time, for example if the content of the corresponding region of the mapped file is changed by this (or another) program. Whether or not such changes occur, and when they occur, is operating-system dependent and therefore unspecified.
All or part of a mapped memory segment may become inaccessible at any time, for example if the backing mapped file is truncated. An attempt to access an inaccessible region of a mapped memory segment will not change the segment's content and will cause an unspecified exception to be thrown either at the time of the access or at some later time. It is therefore strongly recommended that appropriate precautions be taken to avoid the manipulation of a mapped file by this (or another) program, except to read or write the file's content.
- Implementation Note:
- When obtaining a mapped segment from a newly created file, the initialization state of the contents of the block of mapped memory associated with the returned mapped memory segment is unspecified and should not be relied upon.
- Parameters:
path
- the path to the file to memory map.bytesOffset
- the offset (expressed in bytes) within the file at which the mapped segment is to start.bytesSize
- the size (in bytes) of the mapped memory backing the memory segment.mapMode
- a file mapping mode, seeFileChannel.map(FileChannel.MapMode, long, long)
; the chosen mapping mode might affect the behavior of the returned memory mapped segment (seeMappedMemorySegments.force(MemorySegment)
).- Returns:
- a new confined mapped memory segment.
- Throws:
IllegalArgumentException
- ifbytesOffset < 0
,bytesSize < 0
, or ifpath
is not associated with the default file system.UnsupportedOperationException
- if an unsupported map mode is specified.IOException
- if the specified path does not point to an existing file, or if some other I/O error occurs.SecurityException
- If a security manager is installed and it denies an unspecified permission required by the implementation. In the case of the default provider, theSecurityManager.checkRead(String)
method is invoked to check read access if the file is opened for reading. TheSecurityManager.checkWrite(String)
method is invoked to check write access if the file is opened for writing.
-
allocateNative
Creates a new confined native memory segment that models a newly allocated block of off-heap memory with given size and alignment constraint (in bytes). The segment will feature all access modes (seeALL_ACCESS
), and its confinement thread is the current thread (seeThread.currentThread()
).- Implementation Note:
- The block of off-heap memory associated with the returned native memory segment is initialized to zero.
Moreover, a client is responsible to call the
close()
on a native memory segment, to make sure the backing off-heap memory block is deallocated accordingly. Failure to do so will result in off-heap memory leaks. - Parameters:
bytesSize
- the size (in bytes) of the off-heap memory block backing the native memory segment.alignmentBytes
- the alignment constraint (in bytes) of the off-heap memory block backing the native memory segment.- Returns:
- a new confined native memory segment.
- Throws:
IllegalArgumentException
- ifbytesSize < 0
,alignmentBytes < 0
, or ifalignmentBytes
is not a power of 2.
-
ofNativeRestricted
Returns a shared native memory segment whose base address isMemoryAddress.NULL
and whose size isLong.MAX_VALUE
. This method can be very useful when dereferencing memory addresses obtained when interacting with native libraries. The segment will feature theREAD
andWRITE
access modes. Equivalent to (but likely more efficient than) the following code:MemoryAddress.NULL.asSegmentRestricted(Long.MAX_VALUE) .withOwnerThread(null) .withAccessModes(READ | WRITE);
This method is restricted. Restricted methods are unsafe, and, if used incorrectly, their use might crash the JVM or, worse, silently result in memory corruption. Thus, clients should refrain from depending on restricted methods, and use safe and supported functionalities, where possible.
- Returns:
- a memory segment whose base address is
MemoryAddress.NULL
and whose size isLong.MAX_VALUE
. - Throws:
IllegalAccessError
- if the runtime propertyforeign.restricted
is not set to eitherpermit
,warn
ordebug
(the default value is set todeny
).
-