我之前的一篇博客:System.gc()和-XX:+DisableExplicitGC启动参数,以及DirectByteBuffer的内存释放 文章末尾处:提到java NIO包是通过sun.misc.Cleaner和PhantomReference来实现堆外内存的自动释放的。现在我们来学习下Cleaner和PhantomReference的使用,自己封装实现堆外内存的自动释放。
sun.misc.Cleaner是JDK内部提供的用来释放非堆内存资源的API。JVM只会帮我们自动释放堆内存资源,但是它提供了回调机制,通过这个类能方便的释放系统的其他资源。我们先看下如何使用Cleaner。
package direct;
public class FreeMemoryTask implements Runnable
{
private long address = 0;
public FreeMemoryTask(long address)
{
this.addre