Using sun.misc.Unsafe to get the address of the elements of a Java array?

I am struggling to understand the documentation of sun.misc.Unsafe - I assume that since it is not intended for general use, no one was worried about making it readable, but I really need a way to find the address of the element in the array ( so that I can pass a pointer to it on my own code). Has anyone got any working code that does this? Reliability?

+6
source share
3 answers

Instead of using an array, you can use the direct ByteBuffer.allocateDirect () buffer. It has an address in the field, and this address does not change for the life of the ByteBuffer. Direct ByteBuffer uses minimal heap space. You can get the address using reflection.


You can use Unsafe to get the address, the problem is that the GC can move it at any time. Objects are not fixed in memory.

In JNI, you can use special methods to copy data to / from Java objects to avoid this problem (and others). I suggest you use them if you want to exchange data between objects with code C.

+6
source

Here is a working example. However, be careful, as you can easily collapse your JVM with inappropriate use of the Unsafe class.

 import java.lang.reflect.Field; import sun.misc.Unsafe; public class UnsafeTest { public static void main(String... args) { Unsafe unsafe = null; try { Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); unsafe = (sun.misc.Unsafe) field.get(null); } catch (Exception e) { throw new AssertionError(e); } int ten = 10; byte size = 1; long mem = unsafe.allocateMemory(size); unsafe.putAddress(mem, ten); long readValue = unsafe.getAddress(mem); System.out.println("Val: " + readValue); } } 
+6
source

Why? JNI has many features for working with the contents of Java arrays. You do not need to use Sun's undocumented inner classes, which may not be available next week.

+1
source

Source: https://habr.com/ru/post/900318/


All Articles