Java Unsafe.copyMemory java.lang.IllegalArgumentEx

2019-02-25 05:27发布

问题:

I have a problem with copyMemory from Unsafe. I spent 2 days in resolving it but with no result. The code presented below always ends up with "IllegalArgumentException". Can You help me and show where is problem ?

    public void testMemoryCopy() {
    class A {
        public long val = 10;
    }
    A a0 = new A();
    A a1 = new A();

    try {
        long offset = unsafe.objectFieldOffset(A.class.getField("val"));
        unsafe.copyMemory(a0, offset, a1, offset, 8);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    }
}

回答1:

This version of Unsafe.copyMemory unfortunately only works for copying to offheap memory areas (by providing null as destination + a absolute memory address instead of an offsett) or when copying to a primitive array.

When trying to specify anything else but null or a primitve array as third argument you will get an java.lang.IllegalArgumentException.

Alternatively you could use the Unsafe.copyMemory (long srcAddress, long destAddress, long bytes) and directly provide the addresses (which of course is risky as the objects might have moved in the meantime).