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 );
Vortex
  • 789
  • 12
  • 21
  • 1
    There is no "Java unsafe API." Are you referring to `sun.misc.Unsafe`? – Thorn G Jan 10 '16 at 04:16
  • Reading the [following blogpost](http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/) would indicate that it is possible (but also read the conclusion at the bottom of that post). – TT. Jan 10 '16 at 06:00

1 Answers1

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;
}
Vortex
  • 789
  • 12
  • 21