Unsafe.copyMemory失败,发生异常

时间:2018-09-30 06:59:02

标签: java unsafe

我正在尝试比较Object []的System :: arrayCopy与Unsafe :: copyMemory的性能。我认为Unsafe :: copyMemory应该更快,因为它进行的检查较少。但是我什至不能使它工作!您能否帮助我了解以下代码片段在做什么?我使用的JDK是Oracle JDK 1.8。

public static final Unsafe UNSAFE;

static
{
    final Unsafe unsafe;
    try
    {
        final PrivilegedExceptionAction<Unsafe> action =
            () ->
            {
                final Field f = Unsafe.class.getDeclaredField("theUnsafe");
                f.setAccessible(true);

                return (Unsafe)f.get(null);
            };
        unsafe = AccessController.doPrivileged(action);
    }
    catch (final Exception ex)
    {
        throw new RuntimeException(ex);
    }
    UNSAFE = unsafe;
}

public static void main(final String[] args)
{
    final Integer[] a = new Integer[1];
    a[0] = 42;
    final Integer[] b = new Integer[1];
    copyUnsafe(a, 0, b, 0, 1);
    assert a[0] == b[0];
}

public static void copyUnsafe(
    final Object[] src,
    final int srcIndex,
    final Object[] dest,
    final int destIndex,
    final int length)
{
    UNSAFE.copyMemory(
        src,
        Unsafe.ARRAY_OBJECT_BASE_OFFSET + srcIndex * Unsafe.ARRAY_OBJECT_INDEX_SCALE,
        dest,
        Unsafe.ARRAY_OBJECT_BASE_OFFSET + destIndex * Unsafe.ARRAY_OBJECT_INDEX_SCALE,
        length * Unsafe.ARRAY_OBJECT_INDEX_SCALE);
}

当我运行此方法时,将引发以下异常:

Exception in thread "main" java.lang.IllegalArgumentException
at sun.misc.Unsafe.copyMemory(Native Method)
at datastructures.Main.copyUnsafe(Main.java:54)
at datastructures.Main.main(Main.java:43)

感谢任何帮助!

0 个答案:

没有答案