How to free memory using Java Unsafe using Java link?

The Java Unsafe class allows you to allocate memory for an object as follows, but using this method, how would you release the allocated memory when you finish, since it did not specify the memory address ...

Field f = Unsafe.class.getDeclaredField("theUnsafe"); //Internal reference f.setAccessible(true); Unsafe unsafe = (Unsafe) f.get(null); //This creates an instance of player class without any initialization Player p = (Player) unsafe.allocateInstance(Player.class); 

Is there a way to access the memory address from an object reference, maybe the integer returned by the hashCode implementation by default will work, so you can do ...

  unsafe.freeMemory(p.hashCode()); 

doesn't seem right like ...

+3
source share
1 answer
  • The "memory address" of an object reference does not make sense, since objects can move through a bunch of Java.
  • You cannot explicitly free the space allocated by Unsafe.allocateInstance , because this space belongs to the Java Heap, and only Garbage Collector can free it.
  • If you need your own memory management outside of Java Heap, you can use the Unsafe.allocateMemory / Unsafe.freeMemory . They deal with raw memory addresses represented as long . However, this memory is not intended for Java objects.
+8
source

All Articles