What replaces Unsafe.copyMemory(Object, long, Object, long, long) in Java 9+?

Viewed 236

Unsafe.copyMemory(Object, long, Object, long, long) is extremely valuable to be able to quickly copy an object to an address.

Unfortunately, ever since Java 9, only primitive arrays seem to be valid for the first argument. You will get an exception for trying to use other object types:

Exception in thread "main" java.lang.IllegalArgumentException
    at java.base/jdk.internal.misc.Unsafe.invalidInput(Unsafe.java:440)
    at java.base/jdk.internal.misc.Unsafe.checkPrimitiveArray(Unsafe.java:560)
    at java.base/jdk.internal.misc.Unsafe.checkPrimitivePointer(Unsafe.java:579)
    at java.base/jdk.internal.misc.Unsafe.copyMemoryChecks(Unsafe.java:832)
    at java.base/jdk.internal.misc.Unsafe.copyMemory(Unsafe.java:800)
    at jdk.unsupported/sun.misc.Unsafe.copyMemory(Unsafe.java:573)

What is the replacement (with similar performance, if possible) for using this method in such a way for Java 9+?

I was thinking about doing it using Unsafe.getLong(Object, long offset) to read the value from an object, Unsafe.putLong(Object, long offset, long value), i.e.:

void copy(long dest, Object src, long srcSize) {
    long destOffset = 0L;
    while (destOffset < srcSize) {
        long value = unsafe.getLong(src, destOffset);

        long destAddress = dest + destOffset;
        unsafe.putLong(destAddress, value); // JVM crashes here

        destOffset += 8L
    }
}

But this is far slower than the original method.

0 Answers
Related