问题
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...
回答1:
- "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 aslong
. However this memory is not for Java objects.
来源:https://stackoverflow.com/questions/24429777/how-to-free-memory-using-java-unsafe-using-a-java-reference