Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to free memory using Java Unsafe, using a Java reference?

Java Unsafe class allows you to allocate memory for an object as follows, but using this method how would you free up the memory allocated when finished, as it does not provide 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 of accessing the memory address from the object reference, maybe the integer returned by the default hashCode implementation will work, so you could do...

 unsafe.freeMemory(p.hashCode());

doesn't seem right some how...

like image 379
newlogic Avatar asked Dec 11 '22 05:12

newlogic


1 Answers

  • "Memory address" of an object reference does not make sense since objects can move across Java Heap.
  • You cannot explicitly free space allocated by Unsafe.allocateInstance, because this space belongs to Java Heap, and only Garbage Collector can free it.
  • If you want your own memory management outside Java Heap, you may use Unsafe.allocateMemory / Unsafe.freeMemory methods. They deal with raw memory addresses represented as long. However this memory is not for Java objects.
like image 103
apangin Avatar answered Jan 26 '23 01:01

apangin