java 操作内存的类,Java直接内存:在自定义类中使用sun.misc.Cleaner

In Java the memory allocated by NIO direct buffers is freed with sun.misc.Cleaner instances, some special phantom references that are more efficient than object finalization.

Is this cleaner mechanism hardcoded in the JVM only for the direct buffer subclasses, or is it possible to also use cleaners in custom components (writing a custom direct byte buffer for instance)?

Here I am not talking about retrieving the cleaner field of an existing nio direct buffer. I am not talking either about manually freeing the memory. This is about writing a new class that allocates direct memory and has it cleaned efficiently and automatically by the garbage collector mechanism.

解决方案

After spending more time reading the API doc ( http://docs.oracle.com/javase/7/docs/api/java/lang/ref/package-summary.html ) I think I have a more detailed answer:

1) it is possible to reuse sun.misc.Cleaner to perform the efficient cleanup of your own custom classes. You declare the cleaner by calling the provided factory method:

sun.misc.Cleaner.create(Object ob, Runnable cleanup);

For some time I could not get it to work properly, that's because I was moronic enough to define the runnable cleanup code of my cleaner as an anonymous class, that kept a (strong) reference to my referent object, preventing it from ever being "phantom reachable"...

2) There is no other way to implement such efficient cleanup (not even with the help of phantom references)

Indeed the reference handler thread handles instances of sun.misc.Cleaner in a special way:

// Fast path for cleaners

if (r instanceof Cleaner) {

((Cleaner)r).clean();

continue;

}

That means that the cleanup code is called directly from the reference handler thread, while in standard usage, the references must be enqueued by the reference handler thread and then dequeued and processed by another application thread.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值