Java引用

概述

Java的引用分为StrongReference、SoftReference、WeakReference、PhantomReference和FinalReference;

其中StrongRference并没有定义成接口,而其余四种都有相应的接口定义;
这五种引用的使用场景如下:

  • 强引用
    最普遍的引用。如果一个对象具有强引用,垃圾回收器绝不会回收它。当内存空 间不足,Java虚拟机宁愿抛出OutOfMemoryError错误,使程序异常终止,也不会靠随意回收具有强引用的对象来解决内存不足问题。
  • 软引用
    如果内存空间足,则不回收;如果内存空间不足,则会被回收;通常可以用来做为缓存;
  • 弱引用
    一旦发生GC,弱引用对象立即被回收;
  • 虚引用
    虚引用不会影响对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收;

SoftReference和WeakReference

上面提到SoftReference适合用来实现缓存,例如google的guava cache就使用到了WeakReference和SoftReference,在创建cache时可以通过如下方式指定用哪种引用:

//使用WeakReference
CacheBuilder.newBuilder()
                .maximumSize(10000)
                .expireAfterWrite(10, TimeUnit.MINUTES).weakKeys().weakValues()
                .build();
//使用SoftReference
 CacheBuilder.newBuilder()
                .maximumSize(10000)
                .expireAfterWrite(10, TimeUnit.MINUTES).softValues()
                .build();

创建SoftReference和WeakReference的构造函数如下:

public WeakReference(T referent, ReferenceQueue<? super T> q) {
    super(referent, q);
}

可以看到可以传入一个ReferenceQueue对象,那么这个传入到Queue对象到底有什么用呢?如果WeakReference所引用的对象被垃圾回收,Java虚拟机就会把这个WeakReference加入到与之关联的Queue中;

PhantomReference

DirectByteBuffer是JDK提供的堆外内存对象,其构造函数如下:

  DirectByteBuffer(int cap) {   
        super(-1, 0, cap, cap);
        boolean pa = VM.isDirectMemoryPageAligned();
        int ps = Bits.pageSize();
        long size = Math.max(1L, (long)cap + (pa ? ps : 0));
        Bits.reserveMemory(size, cap);

        long base = 0;
        try {
            base = unsafe.allocateMemory(size);
        } catch (OutOfMemoryError x) {
            Bits.unreserveMemory(size, cap);
            throw x;
        }
        unsafe.setMemory(base, size, (byte) 0);
        if (pa && (base % ps != 0)) {
            // Round up to page boundary
            address = base + ps - (base & (ps - 1));
        } else {
            address = base;
        }
        cleaner = Cleaner.create(this, new Deallocator(base, size, cap));
        att = null;
    }

其中的Cleaner对象继承自PhantomReference:

public class Cleaner extends PhantomReference<Object>

那么定义成PhantomReference起什么作用呢?其实主要是为了回收堆外内存,关于其具体的实现,后面会进行介绍;

FinalReference

FinalReference有个子类Finalizer,这两个类的包访问级别都是default而不是public的,因此我们无法在代码中直接调用;
说到FinalReference的使用,就免不了谈及对象的创建:

instanceOop InstanceKlass::allocate_instance(TRAPS) {
  bool has_finalizer_flag = has_finalizer(); //判断当前类是否包含非空的finalize方法
  int size = size_helper(); //确定要分配的内存大小

  KlassHandle h_k(THREAD, this);

  instanceOop i;

  i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
  if (has_finalizer_flag && !RegisterFinalizersAtInit) {
    i = register_finalizer(i, CHECK_NULL);
  }
  return i;
}
instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
  if (TraceFinalizerRegistration) {
    tty->print("Registered ");
    i->print_value_on(tty);
    tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
  }
  instanceHandle h_i(THREAD, i);
  // Pass the handle as argument, JavaCalls::call expects oop as jobjects
  JavaValue result(T_VOID);
  JavaCallArguments args(h_i);
  methodHandle mh (THREAD, Universe::finalizer_register_method());
  JavaCalls::call(&result, mh, &args, CHECK_NULL);
  return h_i();
}

可以看到对象创建时,如果发现对象实现了finalize方法,则会调用Finalizer.register方法,将对象注册到Finalizer的静态属性unfinalized上,形成Finalizer链表;

final class Finalizer extends FinalReference<Object> { 
private static ReferenceQueue<Object> queue = new ReferenceQueue<>();
private static Finalizer unfinalized = null;

private static class FinalizerThread extends Thread {
        private volatile boolean running;
        FinalizerThread(ThreadGroup g) {
            super(g, "Finalizer");
        }
        public void run() {
            if (running)
                return;

            // Finalizer thread starts before System.initializeSystemClass
            // is called.  Wait until JavaLangAccess is available
            while (!VM.isBooted()) {
                // delay until VM completes initialization
                try {
                    VM.awaitBooted();
                } catch (InterruptedException x) {
                    // ignore and continue
                }
            }
            final JavaLangAccess jla = SharedSecrets.getJavaLangAccess();
            running = true;
            for (;;) {
                try {
                    Finalizer f = (Finalizer)queue.remove();
                    f.runFinalizer(jla);
                } catch (InterruptedException x) {
                    // ignore and continue
                }
            }
        }
    }

}

可以看到FinalizerThread线程会从queue队列中获取Finalizer对象,调用其finalize方法;queue即创建Reference时传入的queue对象;

那么,Finalizer什么时候会加入到queue队列呢?很容易想到,当GC发生时,Finalizer对象会加入到queue队列;

那么JVM是如何实现当对象回收时,将对象添加到queue呢?

# Reference
Reference对象是上述对象的基类,它的结构如下:

private T referent;      
volatile ReferenceQueue<? super T> queue;//对象被回收后,Reference会被放入队列
Reference next;
transient private Reference<T> discovered;  /* used by VM */
private static Reference<Object> pending = null;//JVM GC时,会将Reference对象设置到pending上,discovered相当于next,指向下一个Reference对象

static boolean tryHandlePending(boolean waitForNotify) {
        Reference<Object> r;
        Cleaner c;
        try {
            synchronized (lock) {
                if (pending != null) {
                    r = pending;
                    c = r instanceof Cleaner ? (Cleaner) r : null;
                    pending = r.discovered;
                    r.discovered = null;
                } else {
                    if (waitForNotify) {//如果等待,则调用lock.wait方法,当GC时将Reference添加到pending队列时,会调用lock.notify方法,
                        lock.wait();
                    }
                    return waitForNotify;
                }
            }
        } catch (OutOfMemoryError x) {
            Thread.yield();
            return true;
        } catch (InterruptedException x) {
            return true;
        }
        if (c != null) {//如果是Cleaner对象,调用其clean方法释放资源
            c.clean();
            return true;
        }

        ReferenceQueue<? super Object> q = r.queue;
        if (q != ReferenceQueue.NULL) q.enqueue(r);
        return true;
    }

前面提到的DirectByteBuffer内存的释放就是通过JVM GC时将对象添加到pending对象,而Reference中的ReferenceHandler线程会将pending中的对象添加到ReferenceQueue,同时如果发现是Cleaner对象,会调用clean方法释放堆外内存;

对于Finalizer对象,当被添加到ReferenceQueue时,会通过FinalizerThread线程调用finalize方法;因此可以看到Finalizer对象至少要经历两次垃圾回收才能被回收,同时由于FinalizerThread线程的优先级为Thread.MAX_PRIORITY - 2,因此当系统压力较大时,Finalizer对象可能要很久才能被回收;

推荐阅读更多精彩内容