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:
- Memory: the managed heap and the garbage collector (GC).
- Compute: bytecode and strict language semantics that block the CPU from crunching arrays in wide vector batches (SIMD).
- 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:
- “Slow” FFM API writes are a myth. When allocating a fresh 32 MB buffer,
Arena.ofConfinedloses tosun.misc.Unsafeby 1.83×, but only because it is required to zero-fill the memory. Writing to a pre-allocated buffer runs at 1.00× parity. - Multi-threaded
Arena.ofShared()is no slower on reads than single-threadedofConfined()orglobal()—all three clocked in at ~5.13 ms versus 3.47 ms forUnsafe(+48% for mandatory bounds checks on random access). - The Vector API on AVX2 speeds up math by 10.70×—and hits nearly the same speed (10.29×) operating directly on native
MemorySegmentmemory without copying anything into Java arrays. - 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). - 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.
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 (, meaning 1 nanosecond 5.3 cycles):
- 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);
- measured time per operation, ns;
- peak P-core Turbo Boost frequency ().
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 onclose(), but accessible only from the owning thread.Arena.ofShared()— a thread-safe arena: accessible from any thread with deterministicclose().Arena.global()— an “eternal” arena with noclose(); memory lives until the process exits.Arena.ofAuto()— a GC-managed arena, handy when you want an off-heap buffer without callingclose()manually.
In practice, using FFM looks just like standard try-with-resources:
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 involvementThe 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 bytes (, or 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
@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);
}
}
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.allocateMemorycalls systemmallocand hands back memory full of stale garbage from previous allocations.Arena.allocateis 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:
- duration of the full allocate+write cycle and pure write into a pre-allocated buffer (
FFM API), µs; - time spent zero-initializing the buffer, µs;
- total buffer size ();
- 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
- Why is
allocAndWriteUnsafeRaw(1186.7 µs) identical towritePreallocatedUnsafe(1189.4 µs)? At bytes (), our buffer sits just belowglibc’s dynamicM_MMAP_THRESHOLDcap (). After the very first iteration,free()keeps the block cached in user space instead of handing it back to the OS, avoidingmmap/munmapsyscalls and page faults (a buffer larger than 32 MiB would behave differently). - What appears in the
writePreallocatedFFMConfineddisassembly: 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)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)
@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)
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 buffer is slightly larger than the shared L3 cache (roughly 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: (~18.4 cycles per struct);FFM: (~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 0x7f6c5ffdb6973. 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 between them:
- components of the two embeddings being compared (e.g., query and document);
- vector dimensionality (
floatelements); - similarity score from to ( = identical direction, = 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 multiplies and adds per pair, the higher the throughput of the entire search engine.
Each 1536-float vector takes bytes (), so a pair () sits comfortably inside the 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:
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 vector steps.
I benchmarked five variants:
scalarCosine— a plainforloop.vectorBasicCosine— explicit vectorization withFloatVector.fma(...)(one accumulator per sum).vectorOffHeapCosine— the same loop reading directly from an off-heapMemorySegmentwithout copying intofloat[].vectorUnrolled2xCosine— manual 2× loop unrolling with two independent accumulators (d0/d1,a0/a1,b0/b1) overfloat[].vectorOffHeapUnrolled2xCosine— 2× unrolled directly over an off-heapMemorySegment.
Listing 3. Source code for the baseline methods (scalarCosine, vectorBasicCosine, vectorOffHeapCosine)
@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)
// 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 ( 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× |
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 (~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 , that gives a critical path of:
The fact that JMH’s back-to-back calls beat that (, or 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 paired steps () with FMA ops dispatched across ports, the throughput floor drops to:
- number of 256-bit vector steps ( for elements; paired steps under 2× unrolling);
- dependency-chain latency of a single
vfmadd231psinstruction ( cycles on Raptor Cove); - independent FMA operations per paired step (
d0, a0, b0, d1, a1, b1— total); - number of 256-bit FMA execution ports on the core ( ports);
- critical-path estimate for a single isolated call stalled on 4-cycle FMA latency with one accumulator;
- theoretical throughput lower bound when both FMA ports stay busy.
That works out to roughly 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 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, ymm14In the heap version (vectorUnrolled2xCosine), C2 interleaved loads and reused ymm0/ymm1 without touching the stack once—accounting for those 3 nanoseconds.
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:
- Request a 4 KiB page via
mmapwith RW permissions (PROT_READ | PROT_WRITE). - 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. - Flip the page permissions to RX (
PROT_READ | PROT_EXEC) viamprotect. - Wrap the page address in a
MethodHandle(vialinker.downcallHandle, a call “down” from the JVM into native code) and invoke it viainvokeExactlike any regular Java method (freeing the page withmunmapinfinally).
// 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:
89 F8mov eax, edi0x89— opcode forMOV r/m32, r32(copy 32-bit source registerreginto destinationr/m).0xF8— ModR/M byte, which splits in binary into three fields11 | 111 | 000:mod = 11(register-to-register mode, no memory access);reg = 111(register7—EDI, first argument under System V ABI);r/m = 000(register0—EAX, return register).
01 F0add eax, esi0x01— opcode forADD r/m32, r32(addregtor/m).0xF0— ModR/M byte =11 | 110 | 000:mod = 11(register-to-register);reg = 110(register6—ESI, second argument);r/m = 000(register0—EAX).
C3ret- Single-byte near return opcode: pops the return address off the stack and hands control back to the JVM with the sum in
EAX.
- Single-byte near return opcode: pops the return address off the stack and hands control back to the JVM with the sum in
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: 42Not 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.
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
// 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);
}
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
- Java 27 lets you evict GC from the hot path without
Unsafe. On sequential writes and SIMD compute, theFFM API(Arena.ofConfined) hits 1.00× parity withUnsafebecause 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). - Multi-threaded
Arena.ofShared()no longer lagsofConfined()orglobal()on reads. All three hit an identical ~5.13 ms reading a million random structs. Off-heap+Vector APIpushes right up against the AVX2 ceiling. Manual 2× FMA unrolling speeds up cosine similarity by 10.70× onfloat[](76.94 ns) and 10.29× directly overMemorySegment(79.99 ns—only +3.06 ns behind).- 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^Xpage protections, and FFI boundary costs.
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.