Repository navigation
Speed up the safe Java implementation on Java 9+ with a multi-release JAR - #189
Merged
Merged
Conversation
… 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>
Owner
|
might take some time to review this FYI |
Author
Not a problem. Is there something I could do to make this easier for you to review? |
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>
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
SafeUtilsandLZ4SafeUtilsmove into a new internal classnet.jpountz.util.ByteArrays, with the existing byte-by-byte code moved over unchanged.src/java9/net/jpountz/util/ByteArrays.javais the Java 9+ variant, compiled with--release 9intoMETA-INF/versions/9. It uses byte-array-viewVarHandles,Arrays.mismatch, and the overlapping-copy algorithm ofLZ4UnsafeUtils, so every access is still bounds checked and nothing usesUnsafe.SafeUtilsandLZ4SafeUtilsstay single-source and delegate. A future fix tocheckRangeorencodeSequencecan't miss Java 9+.target/classes, whereMETA-INF/versionsdoesn't apply. Failsafe reruns the same tests against the JAR, so the Java 9+ class is tested too.MultiReleaseJarTestchecks that the JAR serves the Java 9ByteArraysand that both variants declare the same public methods.OverlappingMatchTestdecodes 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.META-INF/versions/9/OSGI-INF/MANIFEST.MFwith an emptyRequire-Capability:, becauselz4-java.bndremoves that header. Felix 7.0.5 and Equinox 3.23 both refuse such a bundle.-jpms-multi-release: falseturns those manifests off;java.lang.invoke, the only new import, comes from the boot loader anyway.MultiReleaseJarTestfails if an empty header comes back.META-INF/versions/**.-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.book1is from the Calgary corpus insrc/test-resources;jsonis 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 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:
unsafeInsecureInstance())The speedup comes from executing fewer instructions. With
-prof perfnormon 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 -Pcoveragepasses, running the whole suite againsttarget/classesand again against the JAR. So does the riscv64 leg's flag set with no JDK 7 toolchain.mainJAR and this JAR side by side and made about 600k comparisons over random inputs and mutations on JDK 11, 17 and 25:ByteArrays: safe and fast decompressors, fast and HC compressors, XXH64. 0.85M to 148M executions each, no findings.Open questions for you
VarHandleaccesses throwIndexOutOfBoundsExceptionon JDK 11 andArrayIndexOutOfBoundsExceptionon 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.ByteArrays, sincesrc/java9isn't a project source root.Multi-Release: truesilently 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/calgaryand the JAR under test on the classpath.Created with Claude Opus 5.5 in Claude Code.