栈内存指向了堆内存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()回收。spring
先示例数组
/** * 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。输出结果为:bash
[B@372f7a8d
[B@372f7a8d
null
复制代码
由于咱们把堆内存设置成最大值20m,第一次建立了一个10m的byte数组,第二次建立了一个11m的byte数组,第二次建立的时候堆内存不够用,就回收了以前10m的数组。jvm
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());
}
}
复制代码
输出结果:ide
com.example.demo.quote.M@372f7a8d
null
finalize
复制代码
弱引用垃圾回收器看到就会被回收。弄清楚弱引用先了解一下什么是ThreadLocal,是个本地线程对象,线程存在这个对象就存在,好比在spring的Transactional注解,在为了保证事务不一样的方法中获取的必须是同一个链接对象,这个链接对象就被保存咋ThreadLocal中。咱们看看ThreadLocal的源码。this
/** * 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对象spa
/** * 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的源码。code
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中。
上面的用图画出来就是这个样子,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能够检测到,而后清理堆外内存。