Unsafe.copyMemory(Object, long, Object, long, long)
能够快速将对象复制到地址是非常有价值的。
不幸的是,自Java 9以来,似乎只有原始数组对第一个参数有效。尝试使用其他对象类型时将出现异常:
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)
对于Java 9+,以这种方式使用此方法的替代品是什么(如果可能的话,性能相似)?
我在考虑用
Unsafe.getLong(Object, long offset)
从对象读取值,
Unsafe.putLong(Object, long offset, long value)
即:
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
}
}
但这比最初的方法慢得多。