On this page

During a university lecture recently, I heard a professor (who holds a PhD and teaches software engineering) drop this line:

For certain statically typed languages—such as Java or C# (good languages, fairly low-level, quite reasonable)—...

My immediate instinct was to laugh. A language with a virtual machine, a garbage collector, stack-based bytecode, no pointer arithmetic, and no inline assembly is the textbook definition of high-level.

Still, once you get past the chuckle, it raises a genuinely interesting engineering question: if you strip away Java’s abstractions layer by layer, how close to the bare metal can you actually get in modern Java 27?

In a typical Spring service, three thick walls stand between your code and the CPU:

  1. Memory: the managed heap and the garbage collector (GC).
  2. Compute: bytecode and strict language semantics that block the CPU from crunching arrays in wide vector batches (SIMD).
  3. Execution: the virtual machine itself, isolating your code from OS syscalls and raw machine instructions.

I decided to break through all three walls one by one on OpenJDK 27 (27+35), measure the exact cost of each step on real hardware (Intel Core i5-14600KF) using JMH, and inspect the machine code generated by the JIT compiler to see what happens underneath.

Here is the short version of what I found:

  1. “Slow” FFM API writes are a myth. When allocating a fresh 32 MB buffer, Arena.ofConfined loses to sun.misc.Unsafe by 1.83×, but only because it is required to zero-fill the memory. Writing to a pre-allocated buffer runs at 1.00× parity.
  2. Multi-threaded Arena.ofShared() is no slower on reads than single-threaded ofConfined() or global()—all three clocked in at ~5.13 ms versus 3.47 ms for Unsafe (+48% for mandatory bounds checks on random access).
  3. The Vector API on AVX2 speeds up math by 10.70×—and hits nearly the same speed (10.29×) operating directly on native MemorySegment memory without copying anything into Java arrays.
  4. You can execute raw x86-64 opcodes from pure Java without a single line of C, and Linker.Option.critical(false) cuts the JVM boundary-crossing cost by 3.12× (from 5.40 down to 1.73 ns).
  5. By default, Java keeps you safely insulated from the hardware, but once you disable the guardrails, you can write code close to C performance—though you also have to start thinking like a C programmer, from zeroing memory pages to 4-cycle pipeline latencies.
Reproducing the Experiments
Full source code for all JMH benchmarks (OffHeapBenchmark, VectorBenchmark, MachineCodeBenchmark), MachineCodeDemo, plotting scripts, and JIT assembly dumps are available in the repository: github.com/b1sted/java-below-bytecode.

1. Testbed and Converting Nanoseconds to Clock Cycles

All benchmarks ran on the same idle machine with no background load:

Parameter Value
CPU Intel Core i5-14600KF (Raptor Lake, 14 cores, P-cores up to 5.30 GHz)
P-core capabilities Out-of-Order, 2 AVX2 vector units (256-bit, FMA), no AVX-512
Cache hierarchy L1D: 48 KiB per core · L2: 2 MiB per core · L3: 24 MiB (shared)
RAM 32 GiB DDR4 3800 MT/s
OS & kernel Arch Linux x86_64 (7.2.14-arch1-1)
JVM & benchmarks OpenJDK 27 (27+35-2325, 64-Bit Server VM) · JMH 1.37 (AverageTime, 5 warmups × 1 s, 10 measurements × 1 s, 2 forks)

Guarding Against Dead-Code Elimination and Counting Cycles

To stop C2 from optimizing away “useless” work (DCE), every read and compute benchmark returns a final result (an XOR accumulator or a float), while write benchmarks mutate native memory (an observable side effect).

To express operation costs in CPU clock cycles, I convert nanoseconds using the single-core peak Turbo Boost frequency (5.3 GHz5.3\,\text{GHz}, meaning 1 nanosecond ≈\approx 5.3 cycles):

top=Top⋅fGHz t_{\text{op}} = T_{\text{op}} \cdot f_{\text{GHz}}
where
topt_{\text{op}}
upper bound on operation cost in CPU cycles (assuming sustained peak boost; if the instantaneous clock was lower, the true cycle count is even smaller);
TopT_{\text{op}}
measured time per operation, ns;
fGHzf_{\text{GHz}}
peak P-core Turbo Boost frequency (5.3 GHz5.3\,\text{GHz}).

2. Layer 1. The Memory Wall: Off-Heap, Unsafe, and the Price of FFM Safety

Regular Java objects live on the heap under GC supervision. A million 32-byte structs means a million separate allocations, each carrying an object header (even with Compact Object Headers), scattered references causing pointer chasing, and ongoing GC traversal. To eliminate that overhead and avoid GC pauses, low-latency systems (Netty, Aeron, HFT engines) move data off-heap into a single contiguous block of native process memory, just like in C/C++.

For years, the only way to do this was the internal, unsupported sun.misc.Unsafe class—essentially raw malloc and long addresses with zero safety checks. Java 24–27 is phasing it out (JEP 498): in OpenJDK 27, memory access via Unsafe prints a runtime warning (and can be disabled completely with --sun-misc-unsafe-memory-access=deny), so I explicitly enabled it for these benchmarks using --sun-misc-unsafe-memory-access=allow. The official replacement is the FFM API (Arena and MemorySegment).

In FFM, memory lifetimes are managed by an arena (Arena). It comes in four main flavors:

  • Arena.ofConfined() — a fast thread-confined arena: freed deterministically on close(), but accessible only from the owning thread.
  • Arena.ofShared() — a thread-safe arena: accessible from any thread with deterministic close().
  • Arena.global() — an “eternal” arena with no close(); memory lives until the process exits.
  • Arena.ofAuto() — a GC-managed arena, handy when you want an off-heap buffer without calling close() manually.

In practice, using FFM looks just like standard try-with-resources:

java
try (Arena arena = Arena.ofConfined()) {
    MemorySegment seg = arena.allocate(MEMORY_SIZE);
    seg.set(ValueLayout.JAVA_LONG, offset, value);
} // memory is deterministically freed here without GC involvement

The million-dollar question for Java engineers is simple: how much slower is the safe, official FFM API compared to bare-knuckle Unsafe?

To find out, I allocated a native buffer holding 1,000,000 structs of 32 bytes each—exactly 32,000,00032{,}000{,}000 bytes (32 MB32\,\text{MB}, or 30.52 MiB30.52\,\text{MiB} in binary units matching CPU caches; 4 fields: long, double, long, long)—and benchmarked two workloads: sequential writes and random reads.

Pitfall #1: “Slow” FFM Writes Are an Illusion

Workload (1M records × 32 bytes) sun.misc.Unsafe FFM API (Confined) Ratio
Allocate + write + free 1186.67 ± 10.96 µs 2167.18 ± 35.86 µs 1.83×
Pure write to pre-allocated buffer 1189.42 ± 31.25 µs 1179.68 ± 2.20 µs 1.00× (parity)
Listing 1. Benchmark code: sequential writes (Unsafe vs FFM) with allocation and into a pre-allocated buffer
java
@Benchmark
public long allocAndWriteUnsafeRaw() {
    long addr = unsafe.allocateMemory(MEMORY_SIZE);
    
    for (long i = 0; i < RECORDS; i++) {
        long off = addr + i * RECORD_SIZE;
        unsafe.putLong(off, i);
        unsafe.putDouble(off + 8, 100.5 + i);
        unsafe.putLong(off + 16, 10L);
        unsafe.putLong(off + 24, 1620000000L);
    }
    
    long check = unsafe.getLong(addr);
    unsafe.freeMemory(addr);
    return check;
}

@Benchmark
public long allocAndWriteFFMConfined() {
    try (Arena arena = Arena.ofConfined()) {
        MemorySegment seg = arena.allocate(MEMORY_SIZE);
        
        for (long i = 0; i < RECORDS; i++) {
            long off = i * RECORD_SIZE;
            seg.set(ValueLayout.JAVA_LONG, off, i);
            seg.set(ValueLayout.JAVA_DOUBLE, off + 8, 100.5 + i);
            seg.set(ValueLayout.JAVA_LONG, off + 16, 10L);
            seg.set(ValueLayout.JAVA_LONG, off + 24, 1620000000L);
        }
        
        return seg.get(ValueLayout.JAVA_LONG, 0);
    }
}

@Benchmark
public void writePreallocatedUnsafe() {
    for (long i = 0; i < RECORDS; i++) {
        long off = unsafePtr + i * RECORD_SIZE;
        unsafe.putLong(off, i);
        unsafe.putDouble(off + 8, 100.5 + i);
        unsafe.putLong(off + 16, 10L);
        unsafe.putLong(off + 24, 1620000000L);
    }
}

@Benchmark
public void writePreallocatedFFMConfined() {
    for (long i = 0; i < RECORDS; i++) {
        long off = i * RECORD_SIZE;
        confinedSeg.set(ValueLayout.JAVA_LONG, off, i);
        confinedSeg.set(ValueLayout.JAVA_DOUBLE, off + 8, 100.5 + i);
        confinedSeg.set(ValueLayout.JAVA_LONG, off + 16, 10L);
        confinedSeg.set(ValueLayout.JAVA_LONG, off + 24, 1620000000L);
    }
}
Fig. 1. Sequential write of 1M structs (32 bytes each) into off-heap memory: full allocate-write-free cycle vs writing to a pre-allocated buffer.
Fig. 1. Sequential write of 1M structs (32 bytes each) into off-heap memory: full allocate-write-free cycle vs writing to a pre-allocated buffer.

On the full “allocate → write → free” cycle, FFM looks almost twice as slow (1.83×). But that penalty has nothing to do with memory access speed—it comes from safety guarantees:

  • Unsafe.allocateMemory calls system malloc and hands back memory full of stale garbage from previous allocations.
  • Arena.allocate is required by the FFM specification to zero-initialize the entire segment so your code can never accidentally read leftover data.

In effect, FFM writes to those 32 MB twice: first with zeros (memset), then with your payload. Subtracting the pure write time from the full cycle gives us the actual zeroing bandwidth:

ΔTzero=Talloc+write−Twrite=2167.18−1179.68=987.50 μsBW⁡zero=SbufΔTzero=32 000 000 bytes987.50⋅10−6 s≈32.41 GB/s \Delta T_{\text{zero}} = T_{\text{alloc+write}} - T_{\text{write}} = 2167.18 - 1179.68 = 987.50\,\mu\text{s} \\[6pt] \operatorname{BW}_{\text{zero}} = \frac{S_{\text{buf}}}{\Delta T_{\text{zero}}} = \frac{32\,000\,000\,\text{bytes}}{987.50 \cdot 10^{-6}\,\text{s}} \approx 32.41\,\text{GB/s}
where
Talloc+write, TwriteT_{\text{alloc+write}},\, T_{\text{write}}
duration of the full allocate+write cycle and pure write into a pre-allocated buffer (FFM API), µs;
ΔTzero\Delta T_{\text{zero}}
time spent zero-initializing the buffer, µs;
SbufS_{\text{buf}}
total buffer size (32 000 000 bytes32\,000\,000\,\text{bytes});
BW⁡zero\operatorname{BW}_{\text{zero}}
effective single-threaded zeroing bandwidth, GB/s.

Once the buffer is pre-allocated, C2 recognizes the loop bounds (0 .. 999,999), validates the segment size and owning thread once before the loop (Bounds Check Elision), and emits the exact same tight machine code for MemorySegment as for Unsafe (1.00×). The practical takeaway is clear: to avoid paying 1.83× on the hot path, you don’t need to crawl back to Unsafe—just reuse pre-allocated segments via a buffer pool (or, as a last resort, call native malloc via Linker + MemorySegment.reinterpret).

Under the hood: why Unsafe.allocateMemory paid zero allocation overhead and what C2 emitted
  1. Why is allocAndWriteUnsafeRaw (1186.7 µs) identical to writePreallocatedUnsafe (1189.4 µs)? At 32 000 00032\,000\,000 bytes (≈30.52 MiB\approx 30.52\,\text{MiB}), our buffer sits just below glibc’s dynamic M_MMAP_THRESHOLD cap (32 MiB32\,\text{MiB}). After the very first iteration, free() keeps the block cached in user space instead of handing it back to the OS, avoiding mmap/munmap syscalls and page faults (a buffer larger than 32 MiB would behave differently).
  2. What appears in the writePreallocatedFFMConfined disassembly: before the loop, C2 checks the segment type, arena owner thread, and buffer size; inside the 4× unrolled loop, only direct memory stores remain:
; Before the loop: owner thread check (0x7f5fc3fda940) and bounds check (0x7f5fc3fdaa3b)
  mov    r11, qword ptr [r15 + 0x450]
  cmp    r10, qword ptr [r11]         ; owningThread == currentThread
  jne    0x7f5fc3fdabde               ; UncommonTrapBlob
...
  cmp    r8, 0x1e847e0                ; enough room for 1M structs?
  jbe    0x7f5fc3fdabde               ; UncommonTrapBlob

; Inside the loop (0x7f5fc3fdaa80): zero checks!
  mov    qword ptr [rdi], rbp         ; field 1 (long)
...; convert i -> double + 100.5
  vmovsd qword ptr [rdi + 8], xmm2    ; field 2 (double)
  mov    qword ptr [rdi + 0x10], 0xa  ; field 3 (long)
  mov    qword ptr [rdi + 0x18], 0x608f3d00 ; field 4 (long)
If this C2 disassembly looks cryptic
In my course x86-64 Assembly after C99, each of these pieces is covered separately: how mmap/munmap, memory pages, and the glibc allocator work, registers like r10/r11/r15, unsigned jumps like jbe (control flow and jcc), and bracketed memory addressing such as [rdi + 0x10].

Pitfall #2: Random Access and the Bounds-Check Tax

When read indices are pre-shuffled (randomIndices[i]), the next address is unpredictable, so the JIT can no longer hoist bounds checks out of the loop. To separate the cost of address validation (spatial safety) from arena lifetime tracking (temporal safety), I benchmarked Unsafe against all three arena types:

Random Read (1M structs = 4M field reads) Time (µs / op) Slowdown vs Unsafe
sun.misc.Unsafe 3467.92 ± 7.47 1.00×
FFM (Arena.ofConfined) 5129.00 ± 3.60 1.48× (+47.9%)
FFM (Arena.global) 5133.34 ± 5.11 1.48× (+48.0%)
FFM (Arena.ofShared) 5133.45 ± 4.08 1.48× (+48.0%)
Listing 2. Benchmark code: random reads of 4 fields via an index array (Unsafe vs FFM)
java
@Benchmark
public long readRandomUnsafe() {
    long acc = 0;
    
    for (int i = 0; i < RECORDS; i++) {
        long off = unsafePtr + ((long) randomIndices[i] * RECORD_SIZE);
        acc ^= unsafe.getLong(off);
        acc ^= Double.doubleToRawLongBits(unsafe.getDouble(off + 8));
        acc ^= unsafe.getLong(off + 16);
        acc ^= unsafe.getLong(off + 24);
    }
    
    return acc;
}

@Benchmark
public long readRandomFFMConfined() {
    long acc = 0;
    
    for (int i = 0; i < RECORDS; i++) {
        long off = (long) randomIndices[i] * RECORD_SIZE;
        acc ^= confinedSeg.get(ValueLayout.JAVA_LONG, off);
        acc ^= Double.doubleToRawLongBits(confinedSeg.get(ValueLayout.JAVA_DOUBLE, off + 8));
        acc ^= confinedSeg.get(ValueLayout.JAVA_LONG, off + 16);
        acc ^= confinedSeg.get(ValueLayout.JAVA_LONG, off + 24);
    }
    
    return acc;
}

// readRandomFFMGlobal and readRandomFFMShared share the exact same loop, differing only in the arena (globalSeg / sharedSeg)
Fig. 2. Random read of 1M 32-byte structs (4M field reads) from a 32 MB off-heap buffer: Unsafe vs three Arena modes.
Fig. 2. Random read of 1M 32-byte structs (4M field reads) from a 32 MB off-heap buffer: Unsafe vs three Arena modes.

Two things jump right off the chart here.

First, Arena.ofShared() pays zero read penalty compared to ofConfined() and global()—all three sit right around ~5.13 ms. In modern Java, a shared arena does not perform heavy synchronization on every read (only its close() is expensive, relying on a thread-local handshake across JVM threads to prove no active reads are in flight), while the thread-ownership check in ofConfined() gets hoisted before the loop.

Second, we can pinpoint the exact cost of bounds checking. Our 30.52 MiB30.52\,\text{MiB} buffer is slightly larger than the shared 24 MiB24\,\text{MiB} L3 cache (roughly 78.6%78.6\% fits in cache), and the core hides part of the DRAM latency via Out-of-Order execution. Converting to cycles per 32-byte struct (4 fields) via (1):

  • Unsafe: 3467.92 μs106≈3.47 ns\frac{3467.92\,\mu\text{s}}{10^6} \approx \mathbf{3.47\,\text{ns}} (~18.4 cycles per struct);
  • FFM: 5129.00 μs106≈5.13 ns\frac{5129.00\,\mu\text{s}}{10^6} \approx \mathbf{5.13\,\text{ns}} (~27.2 cycles per struct).

The overhead is +1.66 ns (+48%), or roughly 8.8 cycles per struct (~2.2 cycles per field). That extra time isn’t the cmp + jae instruction itself (a well-predicted branch on x86 is nearly free), but a domino effect: four bounds checks per struct increase register pressure, forcing C2 to unroll the loop less aggressively (2× instead of Unsafe’s 4×) and keeping fewer concurrent cache/RAM requests in flight (memory-level parallelism).

Under the hood: what bounds checks look like in C2 assembly

In readRandomUnsafe, C2 unrolled the loop 4 structs per step, computing all four random addresses upfront without a single conditional branch. In readRandomFFMConfined, the four cmp + jae checks per struct raised register pressure enough that C2 only unrolled 2×, and spilled the segment’s Java object pointer (Oop) into xmm0 on every iteration—just in case it had to bail out to UncommonTrapBlob—to free up general-purpose register r9:

; readRandomFFMConfined (0x7f6c5ffdb4c3): 4 bounds checks per struct + Oop spill to xmm0
  mov    r11d, r9d
  vmovq  r9, xmm0                     ; restore Oop (MemorySegment) before trap
  movsxd rbx, dword ptr [rsi + r11*4 + 0xc]
  shl    rbx, 5
  cmp    rbx, rcx                     ; Check #1 (offset + 0)
  jae    0x7f6c5ffdb5d3               ; UncommonTrapBlob
...
  cmp    rax, rcx                     ; Check #2 (offset + 8)
  jae    0x7f6c5ffdb60f
...
  cmp    r8, rcx                      ; Check #3 (offset + 16)
  jae    0x7f6c5ffdb653
...
  cmp    rbx, rcx                     ; Check #4 (offset + 24)
  jae    0x7f6c5ffdb697

3. Layer 2. The Compute Wall: AVX2 and SIMD over Off-Heap Memory

Okay, our data lives in native memory. Next, we want the CPU to crunch it in wide vector batches rather than one number per cycle (SIMD).

For a real-world workload, I picked the core operation behind semantic search, RAG, and vector databases: cosine similarity between two 1536-dimensional float embeddings.

Put simply, a vector search engine (such as Java-based Apache Lucene) doesn’t match exact substrings like LIKE '%...%' in SQL. It turns both documents and user queries into 1536-float arrays and measures how closely their directions align using the cosine of the angle θ\theta between them:

cos⁡(θ)=∑i=0n−1aibi(∑i=0n−1ai2)⋅(∑i=0n−1bi2)(n=1536) \cos(\theta) = \frac{\sum_{i=0}^{n-1} a_i b_i}{\sqrt{\left(\sum_{i=0}^{n-1} a_i^2\right) \cdot \left(\sum_{i=0}^{n-1} b_i^2\right)}} \qquad (n = 1536)
where
ai, bia_i,\, b_i
components of the two embeddings being compared (e.g., query and document);
nn
vector dimensionality (15361536 float elements);
cos⁡(θ)\cos(\theta)
similarity score from −1-1 to 11 (11 = identical direction, 00 = orthogonal/unrelated).

Cosine similarity depends strictly on the angle between vectors and ignores their magnitude. From a hardware perspective, it is an ideal stress test: searching a database of millions of documents means running this formula millions of times per second. The faster a core burns through 15361536 multiplies and adds per pair, the higher the throughput of the entire search engine.

Each 1536-float vector takes 1536×4=61441536 \times 4 = 6144 bytes (6 KiB6\,\text{KiB}), so a pair (12 KiB12\,\text{KiB}) sits comfortably inside the 48 KiB48\,\text{KiB} L1D cache. That keeps the benchmark 100% compute-bound.

The JIT compiler is forbidden from auto-vectorizing a plain Java for loop here because floating-point addition is not associative. The Vector API (--add-modules jdk.incubator.vector), however, hands you direct control over SIMD registers. Despite its incubator status, this API has compiled down cleanly in C2 to pure vector instructions with zero heap allocations for several releases. On the Core i5-14600KF (where Intel fused off 512-bit AVX-512), FloatVector.SPECIES_PREFERRED selects 256-bit AVX2—8 floats per step—giving us a clean, readable inner loop:

java
for (int i = 0; i < upperBound; i += SPECIES.length()) {
    FloatVector va = FloatVector.fromArray(SPECIES, vectorA, i);
    FloatVector vb = FloatVector.fromArray(SPECIES, vectorB, i);
    vDot = va.fma(vb, vDot); // 8 multiplies and adds in one instruction
}

A 1536-element embedding maps cleanly onto Nvec=1536/8=192N_{\text{vec}} = 1536 / 8 = \mathbf{192} vector steps.

I benchmarked five variants:

  1. scalarCosine — a plain for loop.
  2. vectorBasicCosine — explicit vectorization with FloatVector.fma(...) (one accumulator per sum).
  3. vectorOffHeapCosine — the same loop reading directly from an off-heap MemorySegment without copying into float[].
  4. vectorUnrolled2xCosine — manual 2× loop unrolling with two independent accumulators (d0/d1, a0/a1, b0/b1) over float[].
  5. vectorOffHeapUnrolled2xCosine — 2× unrolled directly over an off-heap MemorySegment.
Listing 3. Source code for the baseline methods (scalarCosine, vectorBasicCosine, vectorOffHeapCosine)
java
@Benchmark
public float scalarCosine() {
    float dot = 0f, normA = 0f, normB = 0f;

    for (int i = 0; i < DIMENSIONS; i++) {
        float a = vectorA[i];
        float b = vectorB[i];
        dot += a * b;
        normA += a * a;
        normB += b * b;
    }

    return dot / (float) Math.sqrt(normA * normB);
}

@Benchmark
public float vectorBasicCosine() {
    int i = 0;
    int upperBound = SPECIES.loopBound(DIMENSIONS);

    FloatVector vDot = FloatVector.zero(SPECIES);
    FloatVector vNormA = FloatVector.zero(SPECIES);
    FloatVector vNormB = FloatVector.zero(SPECIES);

    for (; i < upperBound; i += SPECIES.length()) {
        FloatVector va = FloatVector.fromArray(SPECIES, vectorA, i);
        FloatVector vb = FloatVector.fromArray(SPECIES, vectorB, i);
        vDot = va.fma(vb, vDot);
        vNormA = va.fma(va, vNormA);
        vNormB = vb.fma(vb, vNormB);
    }

    float dot = vDot.reduceLanes(VectorOperators.ADD);
    float normA = vNormA.reduceLanes(VectorOperators.ADD);
    float normB = vNormB.reduceLanes(VectorOperators.ADD);

    for (; i < DIMENSIONS; i++) {
        dot += vectorA[i] * vectorB[i];
        normA += vectorA[i] * vectorA[i];
        normB += vectorB[i] * vectorB[i];
    }

    return dot / (float) Math.sqrt(normA * normB);
}

// Combo: Off-heap MemorySegment + AVX2 without copying to heap
@Benchmark
public float vectorOffHeapCosine() {
    int i = 0;
    int upperBound = SPECIES.loopBound(DIMENSIONS);

    FloatVector vDot = FloatVector.zero(SPECIES);
    FloatVector vNormA = FloatVector.zero(SPECIES);
    FloatVector vNormB = FloatVector.zero(SPECIES);

    for (; i < upperBound; i += SPECIES.length()) {
        long byteOffset = (long) i * Float.BYTES;
        FloatVector va = FloatVector.fromMemorySegment(SPECIES, segA, byteOffset, NATIVE_ORDER);
        FloatVector vb = FloatVector.fromMemorySegment(SPECIES, segB, byteOffset, NATIVE_ORDER);
        vDot = va.fma(vb, vDot);
        vNormA = va.fma(va, vNormA);
        vNormB = vb.fma(vb, vNormB);
    }

    float dot = vDot.reduceLanes(VectorOperators.ADD);
    float normA = vNormA.reduceLanes(VectorOperators.ADD);
    float normB = vNormB.reduceLanes(VectorOperators.ADD);

    for (; i < DIMENSIONS; i++) {
        float a = segA.getAtIndex(ValueLayout.JAVA_FLOAT, i);
        float b = segB.getAtIndex(ValueLayout.JAVA_FLOAT, i);
        dot += a * b;
        normA += a * a;
        normB += b * b;
    }

    return dot / (float) Math.sqrt(normA * normB);
}
Listing 4. Source code for the 2× unrolled methods (vectorUnrolled2xCosine and vectorOffHeapUnrolled2xCosine)
java
// Break the FMA dependency chain: 2 independent accumulators (heap)
@Benchmark
public float vectorUnrolled2xCosine() {
    int i = 0;
    int step = SPECIES.length();
    int unrollStep = step * 2;
    int upperBound = DIMENSIONS - (DIMENSIONS % unrollStep);

    FloatVector d0 = FloatVector.zero(SPECIES), d1 = FloatVector.zero(SPECIES);
    FloatVector a0 = FloatVector.zero(SPECIES), a1 = FloatVector.zero(SPECIES);
    FloatVector b0 = FloatVector.zero(SPECIES), b1 = FloatVector.zero(SPECIES);

    for (; i < upperBound; i += unrollStep) {
        FloatVector va0 = FloatVector.fromArray(SPECIES, vectorA, i);
        FloatVector vb0 = FloatVector.fromArray(SPECIES, vectorB, i);
        FloatVector va1 = FloatVector.fromArray(SPECIES, vectorA, i + step);
        FloatVector vb1 = FloatVector.fromArray(SPECIES, vectorB, i + step);

        d0 = va0.fma(vb0, d0);
        a0 = va0.fma(va0, a0);
        b0 = vb0.fma(vb0, b0);

        d1 = va1.fma(vb1, d1);
        a1 = va1.fma(va1, a1);
        b1 = vb1.fma(vb1, b1);
    }

    float dot = d0.add(d1).reduceLanes(VectorOperators.ADD);
    float normA = a0.add(a1).reduceLanes(VectorOperators.ADD);
    float normB = b0.add(b1).reduceLanes(VectorOperators.ADD);

    for (; i < DIMENSIONS; i++) {
        dot += vectorA[i] * vectorB[i];
        normA += vectorA[i] * vectorA[i];
        normB += vectorB[i] * vectorB[i];
    }

    return dot / (float) Math.sqrt(normA * normB);
}

// Combo x2: Off-heap MemorySegment + 2x FMA unrolling on AVX2
@Benchmark
public float vectorOffHeapUnrolled2xCosine() {
    int i = 0;
    int step = SPECIES.length();
    int unrollStep = step * 2;
    int upperBound = DIMENSIONS - (DIMENSIONS % unrollStep);

    FloatVector d0 = FloatVector.zero(SPECIES), d1 = FloatVector.zero(SPECIES);
    FloatVector a0 = FloatVector.zero(SPECIES), a1 = FloatVector.zero(SPECIES);
    FloatVector b0 = FloatVector.zero(SPECIES), b1 = FloatVector.zero(SPECIES);

    for (; i < upperBound; i += unrollStep) {
        long off0 = (long) i * Float.BYTES;
        long off1 = (long) (i + step) * Float.BYTES;

        FloatVector va0 = FloatVector.fromMemorySegment(SPECIES, segA, off0, NATIVE_ORDER);
        FloatVector vb0 = FloatVector.fromMemorySegment(SPECIES, segB, off0, NATIVE_ORDER);
        FloatVector va1 = FloatVector.fromMemorySegment(SPECIES, segA, off1, NATIVE_ORDER);
        FloatVector vb1 = FloatVector.fromMemorySegment(SPECIES, segB, off1, NATIVE_ORDER);

        d0 = va0.fma(vb0, d0);
        a0 = va0.fma(va0, a0);
        b0 = vb0.fma(vb0, b0);

        d1 = va1.fma(vb1, d1);
        a1 = va1.fma(va1, a1);
        b1 = vb1.fma(vb1, b1);
    }

    float dot = d0.add(d1).reduceLanes(VectorOperators.ADD);
    float normA = a0.add(a1).reduceLanes(VectorOperators.ADD);
    float normB = b0.add(b1).reduceLanes(VectorOperators.ADD);

    for (; i < DIMENSIONS; i++) {
        float a = segA.getAtIndex(ValueLayout.JAVA_FLOAT, i);
        float b = segB.getAtIndex(ValueLayout.JAVA_FLOAT, i);
        dot += a * b;
        normA += a * a;
        normB += b * b;
    }

    return dot / (float) Math.sqrt(normA * normB);
}
Variant (n=1536n = 1536 float) Time (ns / op) Speedup vs Scalar
scalarCosine (heap, scalar) 823.05 ± 0.09 1.00×
vectorBasicCosine (heap, 1 accumulator) 133.20 ± 0.35 6.18×
vectorOffHeapCosine (off-heap MemorySegment) 135.63 ± 0.17 6.07×
vectorOffHeapUnrolled2xCosine (off-heap, 2 accumulators) 79.99 ± 0.02 10.29×
vectorUnrolled2xCosine (heap, 2 accumulators) 76.94 ± 0.16 10.70×
Fig. 3. Cosine similarity latency (1536 floats) on Intel Core i5-14600KF: C2 scalar loop vs AVX2 Vector API with 1 and 2 accumulators in heap and off-heap memory.
Fig. 3. Cosine similarity latency (1536 floats) on Intel Core i5-14600KF: C2 scalar loop vs AVX2 Vector API with 1 and 2 accumulators in heap and off-heap memory.

How an 8-Lane Register Delivered a 10.70× Speedup

At first glance, getting 10.70× speedup out of an 8-lane register looks counterintuitive. Three back-of-the-envelope numbers explain why.

1. A stalled scalar loop. scalarCosine spends 823.05 ns1536≈0.536 ns\frac{823.05\,\text{ns}}{1536} \approx \mathbf{0.536\,\text{ns}} (~2.84 cycles) per float.

The multiplies and adds serialize completely because each iteration has to wait for the running sum from the previous step.

2. A single-accumulator bottleneck (133.20 ns). In vectorBasicCosine, an FMA (vfmadd231ps) instruction can issue every cycle, yet its result takes 4 cycles to land. Think of it as two parallel assembly lines inside the core: if every step depends on the previous step (writing into the same vDot register), one line sits idle while the other waits out all 4 cycles. The disassembly shows C2 unrolled the loop 8× (64 elements per iteration), yet all 24 vfmadd231ps instructions still target the exact same three registers (ymm4, ymm3, ymm2). For a single isolated call at 5.3 GHz5.3\,\text{GHz}, that gives a critical path of:

Tlat=Nvec⋅LFMAfGHz=192⋅45.3 GHz≈144.9 nsJMH streaming measurement: 133.20 ns (speedup 823.05133.20≈6.18×) T_{\text{lat}} = \frac{N_{\text{vec}} \cdot L_{\text{FMA}}}{f_{\text{GHz}}} = \frac{192 \cdot 4}{5.3\,\text{GHz}} \approx 144.9\,\text{ns} \\[4pt] \text{JMH streaming measurement: } 133.20\,\text{ns} \ \left(\text{speedup } \frac{823.05}{133.20} \approx 6.18{\times}\right)

The fact that JMH’s back-to-back calls beat that (133.20 ns133.20\,\text{ns}, or ≈706\approx 706 cycles) is pure Out-of-Order execution: each invocation starts by zeroing the accumulators (vxorps xmm4, xmm4, xmm4), breaking the dependency chain from the previous call. An entire call won’t fit in the 512-entry reorder buffer (ROB), but the tail of one call (the 8-lane horizontal reduction, vsqrtss, vdivss) overlaps with the head of the next, shaving off ~60 cycles at the boundary. Inside the loop itself, the second FMA unit is still twiddling its thumbs.

3. Two accumulators saturate both FMA ports (76.94 ns). Once vectorUnrolled2xCosine introduces two independent accumulators (d0 and d1), both execution pipelines get useful work at the same time: one computes the even vector while the other computes the odd vector. Across 9696 paired steps (192/2192 / 2) with 66 FMA ops dispatched across 22 ports, the throughput floor drops to:

Tthr=(Nvec/2)⋅(kFMA/pFMA)fGHz=96⋅(6/2)5.3 GHz≈54.3 nsJMH measurement: 76.94 ns (speedup 823.0576.94≈10.70×) T_{\text{thr}} = \frac{(N_{\text{vec}} / 2) \cdot (k_{\text{FMA}} / p_{\text{FMA}})}{f_{\text{GHz}}} = \frac{96 \cdot (6 / 2)}{5.3\,\text{GHz}} \approx 54.3\,\text{ns} \\[4pt] \text{JMH measurement: } 76.94\,\text{ns} \ \left(\text{speedup } \frac{823.05}{76.94} \approx 10.70{\times}\right)
where
NvecN_{\text{vec}}
number of 256-bit vector steps (192192 for 15361536 elements; Nvec/2=96N_{\text{vec}} / 2 = 96 paired steps under 2× unrolling);
LFMAL_{\text{FMA}}
dependency-chain latency of a single vfmadd231ps instruction (44 cycles on Raptor Cove);
kFMAk_{\text{FMA}}
independent FMA operations per paired step (d0, a0, b0, d1, a1, b1 — 66 total);
pFMAp_{\text{FMA}}
number of 256-bit FMA execution ports on the core (22 ports);
TlatT_{\text{lat}}
critical-path estimate for a single isolated call stalled on 4-cycle FMA latency with one accumulator;
TthrT_{\text{thr}}
theoretical throughput lower bound when both FMA ports stay busy.

That works out to roughly 0.265 cycles\mathbf{0.265\,\text{cycles}} per float—nearly 4 elements every clock cycle.

Why stop at 2× unrolling instead of pushing to 3× or 4×? With three sums (dot, normA, normB), 2× already creates 6 independent accumulators (6 FMAs across 2 ports = 3 cycles against a 4-cycle pipeline latency, or 75% of theoretical peak). Going to 9 or 12 accumulators runs straight into register pressure: AVX2 on x86-64 only has 16 registers (ymm0–ymm15), and as the disassembly below shows, C2 already starts spilling intermediate vectors to the stack at 6 accumulators in the off-heap variant.

4. Off-heap + SIMD is nearly free. Reading straight from a native MemorySegment in vectorOffHeapUnrolled2xCosine (79.99 ns, 10.29× speedup) trails the float[] array version (76.94 ns) by just ~3.06 ns (+4.0%) (79.993 vs 76.936 ns in the raw JMH output). Vector engines written in Java can store gigabytes of embeddings off-heap—completely invisible to the GC—and still score them at full AVX2 speed.

Keep scale in mind, though: here, a 12 KiB12\,\text{KiB} vector pair sits entirely in L1D, sustaining ~150 GB/s of read bandwidth from a single core. In a real vector database scanning millions of documents (gigabytes spilling out of L3), DRAM bandwidth becomes the bottleneck long before FMA ports do—which is why production engines pair AVX2 with quantization (int8 or binary).

Under the hood: where the 3.06 ns gap between heap and off-heap came from on 2× AVX2

C2 unrolled both vectorUnrolled2xCosine and vectorOffHeapUnrolled2xCosine further to 64 floats per iteration (0x40, 8 vector steps), preserving all 6 accumulators. In vectorOffHeapUnrolled2xCosine, every MemorySegment check is hoisted outside the loop as well, but the instruction scheduler issued loads from the first segment (rbx) ahead of the second (rcx). Between the 6 accumulators, 8 loaded vectors, and loads from rcx, the loop ran out of the 16 ymm registers: the vector at [rbx + 0xe0] gets pushed onto the stack (spill) and reloaded twice, plus the 64-bit base pointers rcx and rbx are recomputed on every 64-element step:

; vectorOffHeapUnrolled2xCosine (0x7f9beffee733): main 64-element loop
  movsxd r9, r10d
  shl    r9, 2
  mov    rcx, r8                      ; recompute base of segment 1
  add    rcx, r9
  mov    rbx, r11                     ; recompute base of segment 2
  add    rbx, r9
...
  vmovups ymm10, ymmword ptr [rbx + 0xe0]
  vmovdqu ymmword ptr [rsp], ymm10    ; stack spill: 16 ymm registers wasn't enough
  vmovups ymm10, ymmword ptr [rbx + 0xa0]
  vmovups ymm11, ymmword ptr [rbx + 0x60]
  vmovups ymm12, ymmword ptr [rbx + 0x20]
  vmovups ymm13, ymmword ptr [rbx + 0xc0]
...
  vmovdqu ymm14, ymmword ptr [rsp]    ; reload #1 (for sum of squares)
  vfmadd231ps ymm4, ymm14, ymm14
...
  vmovdqu ymm6, ymmword ptr [rsp]     ; reload #2 (for dot product)
  vfmadd231ps ymm3, ymm6, ymm14

In the heap version (vectorUnrolled2xCosine), C2 interleaved loads and reused ymm0/ymm1 without touching the stack once—accounting for those 3 nanoseconds.

IEEE 754, pipelines, and AVX2 at the hardware level
My x86-64 assembly course covers this down to instructions and cycles: how float works in IEEE 754 and xmm registers, pipeline dependency chains, and 256-bit AVX2 with ymm registers.

4. Layer 3. The Bytecode Wall: A Mini-JIT Running Raw x86-64 Opcodes

That leaves the final trump card people always bring up in debates about “low-level” languages: in Java, you can’t ask the OS for virtual memory and splice raw machine code right into a method.

True, there is no asm { ... } block in Java syntax. Yet the other half of the FFM API (Linker) lets you call any C function from the standard library directly—including OS memory-management syscalls.

To prove it, I built a bare-bones mini-JIT in pure Java (--enable-native-access=ALL-UNNAMED) obeying the W^X security rule:

  1. Request a 4 KiB page via mmap with RW permissions (PROT_READ | PROT_WRITE).
  2. Write 5 bytes of x86-64 machine code to add two ints (mov eax, edi; add eax, esi; ret) following the System V AMD64 ABI.
  3. Flip the page permissions to RX (PROT_READ | PROT_EXEC) via mprotect.
  4. Wrap the page address in a MethodHandle (via linker.downcallHandle, a call “down” from the JVM into native code) and invoke it via invokeExact like any regular Java method (freeing the page with munmap in finally).
java
// 1. Allocate an RW page via mmap and bind its size in FFM
MemorySegment code = (MemorySegment) mmap.invokeExact(
        MemorySegment.NULL, PAGE_SIZE,
        PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0L
);
code = code.reinterpret(PAGE_SIZE);

// 2. 89 F8 -> mov eax, edi | 01 F0 -> add eax, esi | C3 -> ret
byte[] opcodes = { (byte) 0x89, (byte) 0xF8, 0x01, (byte) 0xF0, (byte) 0xC3 };
MemorySegment.copy(opcodes, 0, code, ValueLayout.JAVA_BYTE, 0, opcodes.length);

// 3. Flip permissions to RX (W^X)
if ((int) mprotect.invokeExact(code, PAGE_SIZE, PROT_READ | PROT_EXEC) != 0) {
    throw new IllegalStateException("mprotect failed");
}

// 4. Invoke the memory page as a function and unmap in finally
try {
    MethodHandle nativeAdd = linker.downcallHandle(
            code,
            FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT)
    );
    int result = (int) nativeAdd.invokeExact(19, 23);
} finally {
    munmap.invokeExact(code, PAGE_SIZE);
}
Where do the bytes 89 F8 01 F0 C3 come from, and how do they decode?

You can get those 5 bytes either by assembling 3 lines with as/nasm and inspecting objdump -d, or by encoding them by hand from the Intel x86-64 opcode table:

  1. 89 F8 →\rightarrow mov eax, edi
    • 0x89 — opcode for MOV r/m32, r32 (copy 32-bit source register reg into destination r/m).
    • 0xF8 — ModR/M byte, which splits in binary into three fields 11 | 111 | 000:
      • mod = 11 (register-to-register mode, no memory access);
      • reg = 111 (register 7 — EDI, first argument under System V ABI);
      • r/m = 000 (register 0 — EAX, return register).
  2. 01 F0 →\rightarrow add eax, esi
    • 0x01 — opcode for ADD r/m32, r32 (add reg to r/m).
    • 0xF0 — ModR/M byte = 11 | 110 | 000:
      • mod = 11 (register-to-register);
      • reg = 110 (register 6 — ESI, second argument);
      • r/m = 000 (register 0 — EAX).
  3. C3 →\rightarrow ret
    • Single-byte near return opcode: pops the return address off the stack and hands control back to the JVM with the sum in EAX.
How ModR/M and the System V ABI work
This encoding is broken down step by step in my x86-64 assembly course: ModR/M byte encoding and the System V AMD64 ABI contract (register and ABI cheatsheet).

Output on our OpenJDK 27 testbed:

Address: 0x7f368d3b0000 | Result from x86-64 opcodes: 42

Not a single line of C, no JNI headers, no gcc—pure Java grabbed a memory page from the Linux kernel and executed machine instructions straight out of it.

Portability Note: x86-64, ARM64, and OS Policies
On x86-64, the instruction and data caches are hardware-coherent, so the code executes immediately after mprotect. On ARM64, you must flush the instruction cache explicitly (__clear_cache) after writing opcodes; on Apple Silicon (macOS), you also need MAP_JIT in mmap, pthread_jit_write_protect_np to toggle permissions, and sys_icache_invalidate. On hardened Linux environments running strict SELinux/W^X policies, mprotect(..., PROT_EXEC) on anonymous pages may also be denied by execmem.

What Does Crossing the JVM Boundary Actually Cost?

Running raw machine code works, but how expensive is the call itself across the Java-to-native border? I benchmarked adding x + y in MachineCodeBenchmark four ways—from an inlined Java expression down to a fast FFM call using Linker.Option.critical(false).

Call Variant (19 + 23) Time (ns / op) Cycles (at 5.3 GHz) Slowdown vs Inline Java
javaAddInline (plain Java, C2 inlined) 0.337 ± 0.006 ~1.8 1.00×
javaAddNoInline (@DontInline method call) 0.692 ± 0.001 ~3.7 2.05×
nativeAddCritical (Linker.Option.critical(false)) 1.728 ± 0.020 ~9.2 5.13×
nativeAddStandard (standard FFM downcall) 5.396 ± 0.083 ~28.6 16.01×
Listing 5. Binding mmap/mprotect/munmap and the 4 MachineCodeBenchmark methods
java
// Binding libc functions via FFM Linker
Linker linker = Linker.nativeLinker();
SymbolLookup stdlib = linker.defaultLookup();

MethodHandle mmap = linker.downcallHandle(
        stdlib.find("mmap").orElseThrow(),
        FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS,
                ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT,
                ValueLayout.JAVA_INT, ValueLayout.JAVA_LONG));

MethodHandle mprotect = linker.downcallHandle(
        stdlib.find("mprotect").orElseThrow(),
        FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS,
                ValueLayout.JAVA_LONG, ValueLayout.JAVA_INT));

MethodHandle munmap = linker.downcallHandle(
        stdlib.find("munmap").orElseThrow(),
        FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.ADDRESS,
                ValueLayout.JAVA_LONG));

// downcallHandle variants for MachineCodeBenchmark
FunctionDescriptor addDesc = FunctionDescriptor.of(
        ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.JAVA_INT);
MethodHandle NATIVE_ADD_STANDARD = linker.downcallHandle(code, addDesc);
MethodHandle NATIVE_ADD_CRITICAL = linker.downcallHandle(
        code, addDesc, Linker.Option.critical(false));

// 4 benchmarked call styles
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
private static int addNoInline(int a, int b) { return a + b; }

@Benchmark
public int javaAddInline() { return x + y; }

@Benchmark
public int javaAddNoInline() { return addNoInline(x, y); }

@Benchmark
public int nativeAddStandard() throws Throwable {
    return (int) NATIVE_ADD_STANDARD.invokeExact(x, y);
}

@Benchmark
public int nativeAddCritical() throws Throwable {
    return (int) NATIVE_ADD_CRITICAL.invokeExact(x, y);
}
Fig. 4. Cost of adding two ints (19 + 23): inlined and non-inlined Java calls vs calling raw x86-64 opcodes via FFM Linker.
Fig. 4. Cost of adding two ints (19 + 23): inlined and non-inlined Java calls vs calling raw x86-64 opcodes via FFM Linker.

A standard Linker call (roughly on par with classic JNI) spends noticeable time on a thread state transition (_thread_in_Java ↔ _thread_in_native) so the garbage collector knows the thread has left managed execution. Passing Linker.Option.critical(false) enables the fast “critical” path (false here forbids passing Java heap objects rather than disabling the option): it promises the JVM that the native function is short-lived and will make no upcalls back into Java, stripping away the state transition:

  • on top of a non-inlined Java call (0.692 ns), a standard FFM downcall adds ~4.70 ns (~25 cycles);
  • with critical(false), that boundary overhead shrinks to ~1.04 ns (~5.5 cycles).

That is a 3.12× speedup—under 2 ns for the entire round trip. And if you pass critical(true) (allowing heap access), FFM even lets you hand a plain byte[] or float[] directly from the Java heap to a short native function with zero off-heap copying—the JVM temporarily pins the array address for the duration of the call.

Even so, the JVM still won’t let you inline raw opcodes straight into a Java loop at 0.34 ns zero-call-overhead speed. Dropping down to native machine code only pays off for substantial operations—syscalls, cryptography, bulk buffer processing—not a pair of arithmetic instructions.


Wrapping Up

  1. Java 27 lets you evict GC from the hot path without Unsafe. On sequential writes and SIMD compute, the FFM API (Arena.ofConfined) hits 1.00× parity with Unsafe because C2 hoists checks outside the loop. You only pay on fresh allocations (mandatory zero-filling, 1.83×) and random access (+48% for per-access bounds checks).
  2. Multi-threaded Arena.ofShared() no longer lags ofConfined() or global() on reads. All three hit an identical ~5.13 ms reading a million random structs.
  3. Off-heap + Vector API pushes right up against the AVX2 ceiling. Manual 2× FMA unrolling speeds up cosine similarity by 10.70× on float[] (76.94 ns) and 10.29× directly over MemorySegment (79.99 ns—only +3.06 ns behind).
  4. So was the professor right? Of course not. By default, Java hides the hardware behind layers of guardrails, and peeling each one back requires explicit JVM flags (--enable-native-access, --add-modules jdk.incubator.vector). Yet once you descend to that level, you end up reasoning about the exact same things a C programmer does: zeroed memory pages, L3 cache capacity, 4-cycle FMA pipeline latencies, W^X page protections, and FFI boundary costs.
Want to learn this layer from scratch?
If you want to read JIT disassembly comfortably, reason about instruction costs, and see what actually happens behind mmap, SIMD, and syscalls, check out my course x86-64 Assembly after C99—covering everything from your first registers and GDB to AVX2, System V ABI, and futex.