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...
Unsafe.allocateInstance
, because this space belongs to Java Heap, and only Garbage Collector can free it.Unsafe.allocateMemory
/ Unsafe.freeMemory
methods. They deal with raw memory addresses represented as long
. However this memory is not for Java objects.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With