棧內存指向了堆內存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能夠檢測到,而後清理堆外內存。