java的四种引用

来源:互联网 发布:网络存储工程师 编辑:程序博客网 时间:2024/04/30 15:28


在java中引用分为4中,强引用(Strong Reference),弱引用(WeakReference),软引用(SoftReference),虚引用(PhantomReference)

1.强引用

        强引用是我们在编程过程中使用的最简单的引用,如代码String s=”abc”中变量s就是字符串对象”abc”     一个强引用。任何被强引用指向的对象都不能被垃圾回收器回收,这些对象都是在程序中需要的。

   2.弱引用

       一个对象只有弱引用指向它,垃圾回收器会立即回收该对象,这是一种急切回收方式。

3.软引用

       软引用指向这些对象,则只有在JVM需要内存时才回收这些对象。软引用可以很好的用来实现缓存。

       4.虚引用

       虚引用的对象可以在任何时候被垃圾回收器回收。

     Java4种引用的级别由高到低依次为:

强引用  >  软引用  >  弱引用  >  虚引用

通过图来看一下他们之间在垃圾回收时的区别:

    ReferenceQueue以及Reference结构分析

     

    ReferenceQueue源码分析

    1.构造方法

public class ReferenceQueue<T> {    /**     * Constructs a new reference-object queue.     */    public ReferenceQueue() { }}
     2.内部类

private static class Null extends ReferenceQueue {        boolean enqueue(Reference r) {            return false;        }    }
static private class Lock { };
     3.部分方法

      

boolean enqueue(Reference<? extends T> r) { /* 只能引用类调用 */        synchronized (r) {            if (r.queue == ENQUEUED) return false;//添加状态,返回false            synchronized (lock) {                r.queue = ENQUEUED;//修改为添加状态                r.next = (head == null) ? r : head;//采用的是头插法                head = r;                queueLength++;                if (r instanceof FinalReference) {                    sun.misc.VM.addFinalRefCount(1);                }                lock.notifyAll();//唤醒所有的线程                return true;            }        }    }

public Reference<? extends T> poll() {//弹出元素        if (head == null)            return null;        synchronized (lock) {            return reallyPoll();//必须获取锁        }    }private Reference<? extends T> reallyPoll() {       /* 必须获取锁,可以看上面的方法 */        if (head != null) {            Reference<? extends T> r = head;            head = (r.next == r) ? null : r.next;            r.queue = NULL;            r.next = r;            queueLength--;            if (r instanceof FinalReference) {                sun.misc.VM.addFinalRefCount(-1);            }            return r;        }        return null;    }


参考:

http://blog.csdn.net/mazhimazh/article/details/19752475

http://www.importnew.com/10866.html




       

0 0
原创粉丝点击