Java Unsafe.copyMemory java.lang.IllegalArgumentException [英] Java Unsafe.copyMemory java.lang.IllegalArgumentException

查看:274
本文介绍了Java Unsafe.copyMemory java.lang.IllegalArgumentException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了来自Unsafe的copyMemory的问题。
我花了两天时间解决它但没有结果。
下面给出的代码总是以IllegalArgumentException结尾。
你能帮助我并显示问题所在吗?

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();
    }
}


推荐答案

这版本 Unsafe.copyMemory 遗憾的是只能复制到offheap内存区域(通过提供 null 作为目标+绝对内存地址而不是offsett)或复制到原始数组时。

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.

当尝试指定除 null 或原始数组作为第三个参数之外的任何其他内容时,您将获得 java.lang.IllegalArgumentException

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

或者你可以使用 Unsafe.copyMemory(long srcAddress,long destAddress,long bytes)并直接提供地址(当然这对象可能已经移动了,这当然有风险)。

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

这篇关于Java Unsafe.copyMemory java.lang.IllegalArgumentException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆