Java中的强软弱虚引用

489 阅读4分钟

Java中的类型引用

强软弱虚

强引用

栈内存指向了堆内存

public class MGCTest {
    public static void main(String[] args) {
        M m = new M();
        m = null;
        System.gc();
    }
}

当栈内存的m指向堆内存的new M(),当m=null是gc触发就会把new M()回收。

软引用

先示例

/**
 * create by yanghongxing on 2020/5/19 11:48 下午
 */
public class SoftReferenceM {
    public static void main(String[] args) throws InterruptedException {
        SoftReference<byte[]> m = new SoftReference<>(new byte[1024 * 1024 * 10]);
        System.out.println(m.get());
        System.gc();
        System.out.println(m.get());
        SoftReference<byte[]> n = new SoftReference<>(new byte[1024 * 1024 * 11]);
        System.out.println(m.get());
      
      	ThreadLocal<M> mThreadLocal = new ThreadLocal<>();
        mThreadLocal.set(new M());
        mThreadLocal.get();
    }
}

我先创建了一个弱引用,这里的引用关系时第一步创建了一个SoftReference对象,第二步创建了一个byte对象,第三 步将将SoftReference通过弱引用指向byte对象,最后将m通过强引用指向SoftReference对象。我们设置一个jvm参数-Xmx20m,将堆内存设置最大值为20m。输出结果为:

[B@372f7a8d
[B@372f7a8d
null

因为我们把堆内存设置成最大值20m,第一次创建了一个10m的byte数组,第二次创建了一个11m的byte数组,第二次创建的时候堆内存不够用,就回收了之前10m的数组。

弱引用

public class WeakReferenceM {
    public static void main(String[] args) {
        WeakReference<M> m = new WeakReference<>(new M());
        System.out.println(m.get());
        System.gc();
        System.out.println(m.get());
    }
}

输出结果:

com.example.demo.quote.M@372f7a8d
null
finalize

弱引用垃圾回收器看到就会被回收。弄清楚弱引用先了解一下什么是ThreadLocal,是个本地线程对象,线程存在这个对象就存在,比如在spring的Transactional注解,在为了保证事务不同的方法中获取的必须是同一个连接对象,这个连接对象就被保存咋ThreadLocal中。我们看看ThreadLocal的源码。

/**
     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * @param value the value to be stored in the current thread's copy of
     *        this thread-local.
     */
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

首先拿到当前线程对象,然后获取了个map,然后往这个map中放了当前对象,这个this就是ThreadLocal对象

 /**
     * Get the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param  t the current thread
     * @return the map
     */
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

t.threadLocals,t是Thread对象,Thread对象的一个成员变量。我们再看看set方法的源码

/**
         * Set the value associated with key.
         *
         * @param key the thread local object
         * @param value the value to be set
         */
        private void set(ThreadLocal<?> key, Object value) {

            // We don't use a fast path as with get() because it is at
            // least as common to use set() to create new entries as
            // it is to replace existing ones, in which case, a fast
            // path would fail more often than not.

            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();

                if (k == key) {
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }

这个构造了个Entry对象,这个Entry可以看成是map的一行数据,一个key-value对。再看看Entry的源码。

static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }

这个Entry对象竟然是继承了WeakReference对象。所以弱引用的典型应用就是ThreadLocal中。

image.png

上面的用图画出来就是这个样子,Thread对象中存了一个强引用指向ThreadLocal就是ThreadLocal mThreadLocal = new ThreadLocal<>()句代码,同时Thread中还有个ThreadLocalMap,这个map的key就是指向ThreadLocal对象,这个对象使用的是弱引用,使用弱引用的原因是防止内存泄漏。既然这里使用的是弱引用为啥ThreadLocal还那么容易产生内存泄漏呢?我们看key是弱引用,但是value不是,所以这个记录还是在map中,所以容易产生内存泄漏,为了防止内存泄漏,我们就在ThreadLocal使用完就remove掉。

虚引用

public class PhontamReferenceM {
    private static ReferenceQueue<M> QUEUE = new ReferenceQueue<>();
    private static List<byte[]> LIST = new ArrayList();


    public static void main(String[] args) {
        PhantomReference<M> m = new PhantomReference<>(new M(), QUEUE);
        new Thread(() -> {
            while (true) {
                LIST.add(new byte[1024 * 1024]);
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("0" + m.get());
            }
        }).start();
        new Thread(() -> {
            while (true) {
                Reference<? extends M> poll = QUEUE.poll();
                if (Objects.nonNull(poll)) {
                    System.out.println("1" + poll);
                }
            }
        }).start();
    }
}

输出为:

0null
1java.lang.ref.PhantomReference@b148489
0null
0null
0null
0null

虚引用的主要作用是管理堆外内存, 比如nio操作为了提高效率就可能有部分内存放在堆外,堆外内存不能直接被GC回收,可能当对象被回收时,通过Queue可以检测到,然后清理堆外内存。