java-math-library icon indicating copy to clipboard operation
java-math-library copied to clipboard

Unsafe deprecated since Java 23

Open TilmanNeumann opened this issue 1 year ago • 4 comments

Most methods of sun.misc.Unsafe have been marked as deprecated in Java 23. It is supposed to replace them with the "Foreign Function & Memory API", see https://openjdk.org/jeps/454.

We need to check if there is a performance-equivalent replacement for the current usage of Unsafe in PSIQS-variants.

TilmanNeumann avatar Jan 24 '25 17:01 TilmanNeumann

I did a few experiments...

At first I tried the FFM (Foreign Function and Memory) API proposed by Java developers to replace sun.misc.Unsafe in handling memory outside the JVM.

More precisely, using GraalVM 23.0.1 I tried MemorySegment sieveArray = Arena.ofConfined().allocate(sieveAllocationSize); and then accessing it via sieveArray.set(ValueLayout.JAVA_BYTE, x2Addr, (byte) (sieveArray.get(ValueLayout.JAVA_BYTE, x2Addr) + logP)); in the sieve phase and sieveArray.get(ValueLayout.JAVA_LONG, x+=8); in the collect phase.

This was very very slow, kind of 100 times slower than the current PSIQS implementations.

TilmanNeumann avatar Aug 24 '25 16:08 TilmanNeumann

Next I noted that the main performance improvement of PSIQS_U vs. PSIQS stems from the sieve:collect phase. The reason is that with Unsafe we can access a byte array as a long array without any copying or conversions. After some study I found that this can be done with a ByteBuffer, too. This approach gives a splendid speedup to the SIQS (not using Unsafe) sieve:collect phase. I'll commit it soon.

Nonetheless, the Unsafe version remains somewhat faster.

TilmanNeumann avatar Aug 24 '25 16:08 TilmanNeumann

I did a few experiments... ... This was very very slow, kind of 100 times slower than the current PSIQS implementations.

My first try was buggy. Now I have reached something like 2-3 times slower than my older implememtations. Work continues...

TilmanNeumann avatar Aug 31 '25 18:08 TilmanNeumann

My latest (unpublished) prototype using the FFM Api is now probably as fast as it could get. But it is still significantly slower than PSIQS_U (using Unsafe) or even PSIQS (using heap memory).

https://inside.java/2025/06/12/ffm-vs-unsafe/ states

  • "a single read/write using FFM is almost 3x slower than Unsafe."
  • "For a “stray” access to a MemorySegment, we cannot expect performance to be on par with Unsafe"

This tells us that a quadratic sieve (doing many "stray" accesses) managing memory with the FFM Api could never get as fast as an Unsafe version. It does not explain though why it is that much slower than plain Java arrays in heap memory.

Maybe the situation gets a bit better in the future, e.g. if https://bugs.openjdk.org/browse/JDK-8362507 gets addressed.

TilmanNeumann avatar Sep 27 '25 10:09 TilmanNeumann