Java unsafe memory copy
Asked Answered
P

1

6

Does Java unsafe API support memcpy from JVM primitive array into direct memory? Note, existing call unsafe.copyMemory() copies from src to dst in the direct memory. I am interested in both writing and reading from direct memory in bulk.

byte src[]=new byte[10];
unsafeRef.copyMemory( src, src_offset, directMemoryOffset, length );
Pugnacious answered 10/1, 2016 at 3:51 Comment(2)
There is no "Java unsafe API." Are you referring to sun.misc.Unsafe?Roybn
Reading the following blogpost would indicate that it is possible (but also read the conclusion at the bottom of that post).Harned
P
4

TT - thanks for reply. It led me to experiment. The built-in function unsafe.copyMemory does copy objects from on-heap to off-heap. Here is my sample code. I was only interested in copying elements so I added 16 as primitive array offset.

byte b[]=new byte[N];
long addressOfObject=getAddressOfObject(unsafe, b);
unsafe.copyMemory(b, 16, null, directOffset, N); 

public long getAddressOfObject(sun.misc.Unsafe unsafe, Object obj) {
    Object helperArray[]    = new Object[1];
    helperArray[0]          = obj;
    long baseOffset         = unsafe.arrayBaseOffset(Object[].class);
    long addressOfObject    = unsafe.getLong(helperArray, baseOffset);      
    return addressOfObject;
}
Pugnacious answered 11/1, 2016 at 4:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.