Java Unsafe.copyMemory java.lang.IllegalArgumentException

∥☆過路亽.° 提交于 2019-12-04 03:54:17

问题


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).



来源:https://stackoverflow.com/questions/41051636/java-unsafe-copymemory-java-lang-illegalargumentexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!