Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java unsafe memory copy

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 );
like image 331
Vortex Avatar asked Jan 10 '16 03:01

Vortex


1 Answers

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;
}
like image 103
Vortex Avatar answered Nov 14 '22 17:11

Vortex