Skip to content

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

Open
Dominik-O22 wants to merge 1 commit into
yawkat:mainfrom
Dominik-O22:safe-java9-mrjar
Open

Dominik-O22 wants to merge 1 commit 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>

This branch has not been deployed

No deployments
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.

1 participant