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

怎甘沉沦 提交于 2019-12-12 08:55:32

问题


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 as long. However this memory is not for Java objects.


来源:https://stackoverflow.com/questions/24429777/how-to-free-memory-using-java-unsafe-using-a-java-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!