0

I am trying to compare the performance of System::arrayCopy vs Unsafe::copyMemory for Object[]. I assume that Unsafe::copyMemory should be faster since it make less checks. However I can't even make it work! Could you pls help me understand what am I doing wrong in the below snippet? JDK I use is 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);
}

When i run this method the following exception is thrown:

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)

Appreciate any help!

Vadim
  • 576
  • 1
  • 4
  • 13
  • Please edit that code into your question instead of having it as a comment. (Ideally, provide a [mcve] instead.) – Jon Skeet Sep 30 '18 at 07:01
  • What is UNSAFE in your code ? Should it be Unsafe ? If yes the method call is wrong because it is not static method. – niemar Sep 30 '18 at 07:04
  • UNSAFE is Unsafe instance - i've added it in snippet. The problem appears in runtime, not in compile time. – Vadim Sep 30 '18 at 07:08
  • 1
    Here is answer on your question, next time try to search https://stackoverflow.com/questions/41051636/java-unsafe-copymemory-java-lang-illegalargumentexception – niemar Sep 30 '18 at 07:32

0 Answers0