Skip to content

Speed up the safe Java implementation on Java 9+ with a multi-release JAR - #189

Merged
yawkat merged 16 commits into
yawkat:mainfrom
Dominik-O22:safe-java9-mrjar
Nov 27, 2026
Merged

yawkat merged 16 commits into
yawkat:mainfrom
Dominik-O22:safe-java9-mrjar

Conversation

@Dominik-O22

Copy link
Copy Markdown

The safe LZ4 and xxHash implementations read and compare one byte at a time, because Java 7 has no bounds-checked way to read several bytes at once. Since unsafeInstance() returns the safe instance, this is the Java code everyone without the native library runs. #35 asked for Java 9 APIs here, and you said a multi-release JAR is fine as long as Java 7 keeps working.

On JDK 11 to 25, LZ4 compression gets 1.25-1.37x faster, decompression 1.16-1.45x, XXH32 1.7-2.2x and XXH64 3-4.4x. JDK 7 and 8 run the same code as before.

Change

  • One versioned class. The byte-array primitives of SafeUtils and LZ4SafeUtils move into a new internal class net.jpountz.util.ByteArrays, with the existing byte-by-byte code moved over unchanged. src/java9/net/jpountz/util/ByteArrays.java is the Java 9+ variant, compiled with --release 9 into META-INF/versions/9. It uses byte-array-view VarHandles, Arrays.mismatch, and the overlapping-copy algorithm of LZ4UnsafeUtils, so every access is still bounds checked and nothing uses Unsafe. SafeUtils and LZ4SafeUtils stay single-source and delegate. A future fix to checkRange or encodeSequence can't miss Java 9+.
  • Tests on both class sets. Surefire tests target/classes, where META-INF/versions doesn't apply. Failsafe reruns the same tests against the JAR, so the Java 9+ class is tested too.
    • MultiReleaseJarTest checks that the JAR serves the Java 9 ByteArrays and that both variants declare the same public methods.
    • OverlappingMatchTest decodes hand-built blocks with match distances 1 to 12 and lengths 4 to 40 on every decompressor, since the new copy handles short distances specially.
  • OSGi. bnd writes a per-release META-INF/versions/9/OSGI-INF/MANIFEST.MF with an empty Require-Capability:, because lz4-java.bnd removes that header. Felix 7.0.5 and Equinox 3.23 both refuse such a bundle. -jpms-multi-release: false turns those manifests off; java.lang.invoke, the only new import, comes from the boot loader anyway. MultiReleaseJarTest fails if an empty header comes back.
  • JaCoCo. The report can't hold two classes with the same name, so it skips META-INF/versions/**.
  • riscv64 CI leg. It now also passes -Dit.test='!net/jpountz/fuzz/*', because failsafe reruns the fuzz regression tests.

Measurements

JMH on a Ryzen 7 9850X3D, pinned to 2 cores, safeInstance(), data split into 64 KiB blocks. book1 is from the Calgary corpus in src/test-resources; json is 1 MiB of synthetic JSON log lines. Each cell is the geometric mean over both data sets. JDK 11 and 25 are two alternating base/JAR pairs each; JDK 8, 17 and 21 are one pair. In every JDK 9+ cell the base and new ranges do not overlap.

JDK 8 JDK 11 JDK 17 JDK 21 JDK 25 JDK 25, C1 only
fast compressor 1.02x 1.34x 1.37x 1.33x 1.37x 1.49x
HC compressor (level 9) 0.98x 1.31x 1.25x 1.30x 1.30x 1.13x
safe decompressor 1.00x 1.37x 1.31x 1.23x 1.22x 1.64x
fast decompressor 1.01x 1.45x 1.40x 1.16x 1.20x 1.62x
XXH32 1.03x 1.72x 2.17x 2.12x 2.15x 3.18x
XXH64 1.00x 3.02x 3.80x 4.38x 4.39x 5.22x

JDK 8 loads the same classes on both sides, so its column shows the noise of a single run. The JSON data gains more than book1, likely because its matches are longer: safe decompression 1.35x vs 1.11x on JDK 25.

Throughput in MB/s on JDK 25, against the other implementations:

safe before safe after Unsafe (unsafeInsecureInstance()) native
fast compressor 466 637 749 1,053
HC compressor 46 60 62 101
safe decompressor 1,397 1,706 2,245 7,077
XXH32 6,081 13,088 9,005 15,363
XXH64 5,795 25,444 24,011 30,814

The speedup comes from executing fewer instructions. With -prof perfnorm on JDK 25, instructions per operation drop by the same factor as cycles in every benchmark (fast compressor 0.68x vs 0.69x, XXH64 0.19x vs 0.19x), and IPC stays between 3.4 and 4.8 on both sides.

Verification

  • ./mvnw verify -Pcoverage passes, running the whole suite against target/classes and again against the JAR. So does the riscv64 leg's flag set with no JDK 7 toolchain.
  • A differential test loaded the main JAR and this JAR side by side and made about 600k comparisons over random inputs and mutations on JDK 11, 17 and 25:
    • The compressors (fast, and HC levels 1 to 17) produce identical bytes.
    • Decompressors and xxHash return the same results, and throw the same exception types on corrupted input.
    • Neither JAR writes outside the destination range it was given.
    • Bytes past the decoded length can differ. Both versions already use that space as scratch for the wild copies.
  • Jazzer, 2 minutes per target against the Java 9 ByteArrays: safe and fast decompressors, fast and HC compressors, XXH64. 0.85M to 148M executions each, no findings.
  • Felix 7.0.5 and Equinox 3.23 resolve and start the bundle and round-trip data. They load the Java 9 class on JDK 11 and 25, and the base class on JDK 8.

Open questions for you

  • CI tests only on JDK 25. Out-of-range VarHandle accesses throw IndexOutOfBoundsException on JDK 11 and ArrayIndexOutOfBoundsException on 25. The one place that catches it now catches the superclass, and the differential test found no difference on 11. A JDK 11 test leg would keep it that way, if you want one.
  • The sources JAR only has the Java 7 ByteArrays, since src/java9 isn't a project source root.
  • Shaded JARs whose manifest drops Multi-Release: true silently fall back to the Java 7 code. That's worth a line in the release notes.
JMH benchmark

Run with -Dcalgary.dir=src/test-resources/calgary and the JAR under test on the classpath.

package bench;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4FastDecompressor;
import net.jpountz.lz4.LZ4SafeDecompressor;
import net.jpountz.xxhash.XXHash32;
import net.jpountz.xxhash.XXHash64;
import net.jpountz.xxhash.XXHashFactory;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;

/** Every benchmark processes the whole data set as independent 64 KiB blocks; MB/s = score * bytes / 1e6. */
@State(Scope.Benchmark)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
public class SafeBench {
  static final int BLOCK = 64 * 1024;

  @Param({"book1", "geo", "pic", "json"})
  public String data;

  /** safe, unsafe (the insecure Unsafe instance, for reference) or native. */
  @Param({"safe"})
  public String impl;

  byte[][] blocks;
  byte[][] fastBlocks;
  int[] fastLens;
  byte[][] hcBlocks;
  int[] hcLens;
  byte[] out;
  LZ4Compressor fast, hc;
  LZ4SafeDecompressor safeDecompressor;
  LZ4FastDecompressor fastDecompressor;
  XXHash32 xxh32;
  XXHash64 xxh64;

  @Setup
  @SuppressWarnings("deprecation")
  public void setup() throws IOException {
    LZ4Factory lz4 = impl.equals("safe") ? LZ4Factory.safeInstance()
        : impl.equals("unsafe") ? LZ4Factory.unsafeInsecureInstance() : LZ4Factory.nativeInstance();
    XXHashFactory xxh = impl.equals("safe") ? XXHashFactory.safeInstance()
        : impl.equals("unsafe") ? XXHashFactory.unsafeInstance() : XXHashFactory.nativeInstance();
    fast = lz4.fastCompressor();
    hc = lz4.highCompressor();
    safeDecompressor = lz4.safeDecompressor();
    fastDecompressor = lz4.fastDecompressor();
    xxh32 = xxh.hash32();
    xxh64 = xxh.hash64();

    byte[] all = load(data);
    List<byte[]> list = new ArrayList<>();
    for (int off = 0; off < all.length; off += BLOCK) {
      list.add(Arrays.copyOfRange(all, off, Math.min(all.length, off + BLOCK)));
    }
    blocks = list.toArray(new byte[0][]);
    out = new byte[fast.maxCompressedLength(BLOCK)];
    fastBlocks = new byte[blocks.length][];
    fastLens = new int[blocks.length];
    hcBlocks = new byte[blocks.length][];
    hcLens = new int[blocks.length];
    LZ4SafeDecompressor reference = LZ4Factory.safeInstance().safeDecompressor();
    for (int i = 0; i < blocks.length; i++) {
      fastBlocks[i] = fast.compress(blocks[i]);
      fastLens[i] = fastBlocks[i].length;
      hcBlocks[i] = hc.compress(blocks[i]);
      hcLens[i] = hcBlocks[i].length;
      check(Arrays.equals(blocks[i], reference.decompress(fastBlocks[i], blocks[i].length)), "fast round trip");
      check(Arrays.equals(blocks[i], reference.decompress(hcBlocks[i], blocks[i].length)), "hc round trip");
      check(Arrays.equals(blocks[i], safeDecompressor.decompress(fastBlocks[i], blocks[i].length)), "safe decompress");
      check(Arrays.equals(blocks[i], fastDecompressor.decompress(hcBlocks[i], blocks[i].length)), "fast decompress");
      check(xxh32.hash(blocks[i], 0, blocks[i].length, 0) == XXHashFactory.safeInstance().hash32().hash(blocks[i], 0, blocks[i].length, 0), "xxh32");
    }
  }

  static void check(boolean ok, String what) {
    if (!ok) {
      throw new AssertionError(what);
    }
  }

  static byte[] load(String name) throws IOException {
    if (name.equals("json")) {
      return syntheticJson(1 << 20);
    }
    return Files.readAllBytes(Paths.get(System.getProperty("calgary.dir"), name));
  }

  /** Deterministic JSON log lines, roughly what a log or search engine compresses. */
  static byte[] syntheticJson(int size) {
    Random r = new Random(42);
    String[] levels = {"INFO", "WARN", "DEBUG", "ERROR"};
    String[] services = {"api-gateway", "search", "indexer", "auth", "billing", "ingest"};
    String[] paths = {"/v1/search", "/v1/index/_bulk", "/health", "/v1/docs/", "/login", "/v2/query"};
    StringBuilder sb = new StringBuilder(size + 512);
    long ts = 1_700_000_000_000L;
    while (sb.length() < size) {
      ts += r.nextInt(50);
      sb.append("{\"@timestamp\":").append(ts)
        .append(",\"level\":\"").append(levels[r.nextInt(levels.length)])
        .append("\",\"service\":\"").append(services[r.nextInt(services.length)])
        .append("\",\"trace_id\":\"").append(Long.toHexString(r.nextLong()))
        .append("\",\"http\":{\"method\":\"").append(r.nextInt(4) == 0 ? "POST" : "GET")
        .append("\",\"path\":\"").append(paths[r.nextInt(paths.length)]).append(r.nextInt(1000))
        .append("\",\"status\":").append(r.nextInt(10) == 0 ? 500 : 200)
        .append(",\"latency_ms\":").append(r.nextInt(2000))
        .append("},\"message\":\"request completed for user ").append(r.nextInt(100000))
        .append("\"}\n");
    }
    return Arrays.copyOf(sb.toString().getBytes(StandardCharsets.UTF_8), size);
  }

  @Benchmark
  public void compressFast(Blackhole bh) {
    for (byte[] b : blocks) {
      bh.consume(fast.compress(b, 0, b.length, out, 0, out.length));
    }
  }

  @Benchmark
  public void compressHC(Blackhole bh) {
    for (byte[] b : blocks) {
      bh.consume(hc.compress(b, 0, b.length, out, 0, out.length));
    }
  }

  @Benchmark
  public void decompressSafe(Blackhole bh) {
    for (int i = 0; i < blocks.length; i++) {
      bh.consume(safeDecompressor.decompress(fastBlocks[i], 0, fastLens[i], out, 0, out.length));
    }
  }

  @Benchmark
  @SuppressWarnings("deprecation")
  public void decompressFast(Blackhole bh) {
    for (int i = 0; i < blocks.length; i++) {
      bh.consume(fastDecompressor.decompress(fastBlocks[i], 0, out, 0, blocks[i].length));
    }
  }

  @Benchmark
  public void xxhash32(Blackhole bh) {
    for (byte[] b : blocks) {
      bh.consume(xxh32.hash(b, 0, b.length, 0));
    }
  }

  @Benchmark
  public void xxhash64(Blackhole bh) {
    for (byte[] b : blocks) {
      bh.consume(xxh64.hash(b, 0, b.length, 0));
    }
  }
}

Created with Claude Opus 5.5 in Claude Code.

… JAR

The safe LZ4 and xxHash implementations read and compare one byte at a
time, because Java 7 has no bounds-checked multi-byte array access.
LZ4Factory.unsafeInstance() returns the safe instance, so this is the
Java path for everyone without the native library.

Move the byte-array primitives of SafeUtils and LZ4SafeUtils into
net.jpountz.util.ByteArrays and add a Java 9+ variant of that class in
META-INF/versions/9. It uses byte-array-view VarHandles,
Arrays.mismatch, and the overlapping-copy algorithm of LZ4UnsafeUtils,
so every access stays bounds checked. Java 7 and 8 keep the existing
code.

The build compiles src/java9 with --release 9 and marks the JAR
Multi-Release. Failsafe reruns the tests against the JAR so the Java 9+
class is tested too. bnd no longer writes per-release OSGi manifests,
whose empty Require-Capability header Felix and Equinox reject, and the
JaCoCo report skips META-INF/versions.

Closes yawkat#35

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@yawkat

yawkat commented Nov 24, 2026

Copy link
Copy Markdown
Owner

might take some time to review this FYI

@Dominik-O22

Copy link
Copy Markdown
Author

might take some time to review this FYI

Not a problem. Is there something I could do to make this easier for you to review?

yawkat and others added 13 commits November 27, 2026 09:53
The test compared only public methods, so a package-private method or a
field added to the Java 7 ByteArrays but missing from the Java 9 one
passed the test and then failed with NoSuchMethodError or
NoSuchFieldError on Java 9+. Compare all methods and fields that other
classes can reach, that is everything except private and synthetic
members.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
readShortLE, writeShortLE, readIntBE, readIntLE, readInt and readLongLE
are called only from SafeUtils in the same package, and SafeUtils
already exposes them. Public, they would become a second copy of that
API on an exported type that could only be deprecated, never removed.
MultiReleaseJarTest now also compares package-private members, so the
two variants are still checked against each other.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each of the three tests repeated the same assumeTrue on lz4.testJar.
A class-level @EnabledIfSystemProperty says it once and reports the
tests as disabled with the reason, not as aborted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
OverlappingMatchTest repeated the decode-and-compare loop of
LZ4Test.assertAllDecode. Use that helper instead. It also decodes into a
destination 64 bytes larger than needed and through the ByteBuffer
methods, which covers the match copies that write past the end of the
match while there is room for it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The switch on distances 1 to 3 moved matchOff back and forth and kept a
separate dec variable. The net effect is two small adjustments: the
second 4-byte copy reads from matchOff + 2 for distance 2 and from
matchOff + 1 otherwise, and distance 3 then moves on by one more byte so
that matchOff trails dOff by 9. Write that directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Both variants agree for every argument the library passes, but not
outside of that: the Java 9 copy8Bytes reads all 8 bytes before writing,
readIntEquals and commonBytes check their whole range up front, and
wildIncrementalCopy writes different bytes past the end of the match.
Write down the preconditions on both copies, so that a new caller does
not rely on behaviour that only one variant has.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Most calls of commonBytes end within a few bytes: on Calgary book1,
61% return 0 and 99.8% return 7 or less. Arrays.mismatch has a fixed
setup cost per call, so the HC compressor gained nothing on text. Compare
the first 8 bytes as one long and call Arrays.mismatch only past them,
and use a byte loop when fewer than 8 bytes are left.

JDK 25 on x86-64, Calgary book1 in 64 KiB blocks, MB/s:

              base     PR   this
  fast         169    187    241
  HC 9        19.9   19.9   25.1
  HC 17       19.8   19.5   24.5

geo improves by 2-5%. Under C1 (-XX:TieredStopAtLevel=1) HC on book1
goes from 11.3 to 12.3 MB/s, still below the 13.8 of the byte loop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
HotSpot ports that run with UseUnalignedAccesses off, such as 32-bit
ARM and riscv64 on JDK 21, do not compile byte array VarHandle views
and Arrays.mismatch to wide accesses. There the Java 9 variant was much
slower than the byte loops it replaces. Utils.isUnalignedAccessAllowed()
already lists the architectures with fast unaligned access, so fall back
to the Java 7 byte loops everywhere else. The check is a static final
boolean, so the JIT drops the unused branch.

Emulated on JDK 25 x86-64 with -XX:-UseUnalignedAccesses
-XX:-UseVectorizedMismatchIntrinsic -Dos.arch=riscv64, Calgary book1 in
64 KiB blocks, MB/s:

                base     PR   this
  fast           167    103    167
  HC 9          20.4   11.3   19.5
  safe decomp    538    227    506
  xxhash64      3495   5926   3491

xxhash64 loses the gain the VarHandle reads still had in this emulation.
On x86-64 the results are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The JaCoCo report excluded META-INF/versions, because one report cannot
hold two classes of the same name. So the coverage summary and badge
never showed untested branches of the class that Java 9+ users run,
although the failsafe run already records probes for it. Add a second
report with only META-INF/versions/9 in target/site/jacoco-java9, and
sum both reports in the CI summary and the published badge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The failsafe execution reran every test against the multi-release jar,
which roughly doubled the test time on every CI leg: 88 s on x86-64,
136 s on aarch64 and 968 s on riscv64 in the PR's CI run. A large part
of that is the stream tests, which mostly go through the JNI code via
fastestInstance() and are not affected by the jar layout. Limit the
rerun to the tests of the safe Java implementations, the xxhash tests,
the fuzz regression tests and MultiReleaseJarTest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
surefire and failsafe are released together, and the PR added failsafe
with its own copy of the surefire version. Use one surefire.version
property for both and for the fuzz profile, so an update cannot move
them apart. fuzz_runner.py read the literal <version> of surefire, so
it now resolves a property reference there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CI passes -Dsurefire.reportFormat=plain so that the log lists every
test, but failsafe reads failsafe.reportFormat, so the jar run only
printed a summary per class. Pass both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The multi-release layout itself causes problems with some tools, which
lz4-java cannot fix on its side: maven-shade-plugin relocates the class
in META-INF/versions/9 but not its path, jdeps refuses multi-release jars
without --multi-release, and tools that only read Java 8 class files
reject the Java 9 class. Say how to work around each. Also mention that
the faster Java 9 code is only used on platforms with fast unaligned
access.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
yawkat and others added 2 commits November 27, 2026 16:31
An enum with no constants still exposes values() and valueOf() on a
public class. A final class with a private constructor does not. The
javadoc now says the class is not part of the public API: it is public
only because net.jpountz.lz4 uses it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Java 9 ByteArrays fell back to copies of the Java 7 method bodies
where unaligned access is not allowed. The byte loops now live once, in
the package-private PortableByteArrays: the Java 7 ByteArrays calls it
for everything, the Java 9 one where unaligned access is not allowed.
The extra call is inlined by the JIT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@yawkat
yawkat merged commit f6918c5 into yawkat:main Nov 27, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants