VarHandle ByteArrayViewVarHandle Access

Read and write multi-byte integers in a byte[] buffer using byteArrayViewVarHandle with explicit ByteOrder and aligned atomic CAS checks.

JavaData Integrity

Code

snippet
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.nio.ByteOrder;
import java.util.HexFormat;

public class PacketIntViews {

    public static void main(String[] args) {
        VarHandle bigInt = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.BIG_ENDIAN);
        VarHandle littleInt = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.LITTLE_ENDIAN);

        byte[] packet = new byte[12];

        // Plain get/set accepts any in-bounds byte offset, even unaligned offsets like 2
        bigInt.set(packet, 2, 0x01020304);
        System.out.println("raw slice: " + HexFormat.of().formatHex(packet, 2, 6));
        System.out.println("as big-endian:    0x" + Integer.toHexString((int) bigInt.get(packet, 2)));
        System.out.println("as little-endian: 0x" + Integer.toHexString((int) littleInt.get(packet, 2)));

        // Aligned offset 0 supports volatile/CAS modes directly on byte[]
        bigInt.setVolatile(packet, 0, 42);
        boolean swapped = bigInt.compareAndSet(packet, 0, 42, 99);
        System.out.println("aligned cas ok: " + swapped + ", header=" + (int) bigInt.getVolatile(packet, 0));

        // Atomic CAS at unaligned byte offset throws IllegalStateException
        try {
            bigInt.compareAndSet(packet, 2, 0x01020304, 0);
        } catch (IllegalStateException ex) {
            System.out.println("unaligned cas rejected: " + ex.getClass().getSimpleName());
        }
    }
}

Execution path — VarHandle ByteArrayViewVarHandle Access

VarHandle ByteArrayViewVarHandle Access keeps everything in the class PacketIntViews and the function main.

Caveats

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.

Applying it

The run prints raw slice:, as big-endian: 0x, as little-endian: 0x — each prefix names the step that produced it.

Statements that matter

VarHandle littleInt = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.LITTLE_ENDIAN);
VarHandle bigInt = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.BIG_ENDIAN);
boolean swapped = bigInt.compareAndSet(packet, 0, 42, 99);

Interactive Tools for This Topic

FAQ

What does VarHandle ByteArrayViewVarHandle Access print when run?
Invoke the file as-is — the `raw slice:`, `as big-endian: 0x`, `as little-endian: 0x` prefixes identify which step printed each line.