如何使用Java引用使用Java Unsafe释放内存? [英] How to free memory using Java Unsafe, using a Java reference?

查看:388
本文介绍了如何使用Java引用使用Java Unsafe释放内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java Unsafe类允许您按如下方式为对象分配内存,但是使用此方法如何释放已完成时分配的内存,因为它不提供内存地址...

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);

有没有办法从对象引用访问内存地址,也许是默认返回的整数hashCode实现可以工作,所以你可以做...

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...

推荐答案


  • 对象引用的内存地址没有意义,因为对象可以跨Java堆移动。

  • 您无法显式释放 Unsafe.allocateInstance 分配的空间,因为此空间属于Java堆,只有垃圾收集器可以释放它。

  • 如果您想在Java堆外部进行自己的内存管理,可以使用 Unsafe.allocateMemory / Unsafe.freeMemory 方法。它们处理表示为 long 的原始内存地址。但是这个内存不适用于Java对象。

    • "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.
    • 这篇关于如何使用Java引用使用Java Unsafe释放内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆