ByteBuffer alignedSlice() in Java

alignedSlice(): This method is available in java.nio.ByteBuffer class of Java.

Syntax:

ByteBuffer java.nio.ByteBuffer.alignedSlice(int unitSize)

Creates a new byte buffer whose content is a shared and aligned subsequence of this buffer's content. The content of the new buffer will start at this buffer's current position rounded up to the index of the nearest aligned byte for the given unit size.

Note: The new buffer will be direct if, and only if, this buffer is direct, and it will be read-only if, and only if, this buffer is read-only.

Parameters: One parameter is required for this method.

unitSize: The unit size in bytes, must be a power of 2.

Returns: The new byte buffer.

Throws:

1. IllegalArgumentException - If the unit size is not a power of 2.

2. UnsupportedOperationException - If the native platform does not guarantee stable aligned slices for the given unit size when managing the memory regions of buffers of the same kind as this buffer (direct or non-direct).

Approach 1: When no exceptions.

Java

import java.nio.ByteBuffer;

public class ByteBufferalignedSlice {
    public static void main(String[] args) {

        byte array[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(array);

        int unitSize = 8;
        System.out.println(bb.alignedSlice(unitSize));

    }
}

Output:

java.nio.HeapByteBuffer[pos=0 lim=0 cap=0]


Approach 2: IllegalArgumentException 

Java

public class ByteBufferalignedSlice {
    public static void main(String[] args) {

        byte array[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(array);

        int unitSize = 7;
        System.out.println(bb.alignedSlice(unitSize));

    }
}


Output:

Exception in thread "main" java.lang.IllegalArgumentException: Unit size not a power of two: 7 at java.base/java.nio.ByteBuffer.alignmentOffset(ByteBuffer.java:2033) at java.base/java.nio.ByteBuffer.alignedSlice(ByteBuffer.java:2103)


Approach 3: UnsupportedOperationException

Java

import java.nio.ByteBuffer;

public class ByteBufferalignedSlice {
    public static void main(String[] args) {

        byte array[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(array);

        int unitSize = 16;
        System.out.println(bb.alignedSlice(unitSize));

    }
}


Output:

Exception in thread "main" java.lang.UnsupportedOperationException: Unit size unsupported for non-direct buffers: 16 at java.base/java.nio.ByteBuffer.alignmentOffset(ByteBuffer.java:2035) at java.base/java.nio.ByteBuffer.alignedSlice(ByteBuffer.java:2103)


No comments:

Post a Comment