强引用

当内存不足时,JVM开始垃圾回收,对于强引用的对象,就算是OOM也不会回收。

95%中都是强引用,如下所示

Object obj=new Object();

软引用

    软引用是一种相对强引用弱化了一些的引用,需要用java.lang.ref.SoftReference类来实现。

    当系统内存充足时,他不会被回收;当系统内存不足时,他会回收。

当内存充足时,他不会被回收

public static void main(String[] args) {

// 强引用
Object obj = new String("hello");
// 软引用
SoftReference softReference = new SoftReference(obj);
obj = null;
System.gc();
System.out.println(obj); // null
System.out.println(softReference.get()); // hello
}

当内存不时,他会被回收 

// -Xmx5m -Xms5m
public static void main(String[] args) {

// 强引用
Object obj = new String("hello");
// 软引用
SoftReference softReference = new SoftReference(obj);
obj = null;
try {
byte[] data = new byte[5 * 1024 * 1024];
} catch (Exception e) {
} finally {
System.out.println(obj); // null
System.out.println(softReference.get()); // null
}
}

弱引用

 对于弱引用的对象来说,只要GC,不管JVM的内存空间是否足够,都会回收该对象占用的内存

public static void main(String[] args) {

// 强引用
Object obj = new String("hello");
// 弱引用
WeakReference weakReference = new WeakReference(obj);

obj = null;
System.gc();
System.out.println(weakReference.get());
}

WeakHashMap

public static void main(String[] args) {

Map map=new WeakHashMap();
Integer key= new Integer(1);
String value = "hashMap";
map.put(key, value);
key=null;
System.gc();
System.out.println(map);//{}
}

只所以一GC,WeakHashmap中的数据就会清空,因为

WeakHashmap.中的Entry是
Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V>

虚引用

虚引用的作用主要跟踪对象垃圾回收的状态。

其中DirectBuffer的释放就是虚引用的使用场景。

ByteBuffer buffer = ByteBuffer.allocateDirect(16);

参考

​尚硅谷Java大厂面试题第2季,面试必刷,跳槽大厂神器_哔哩哔哩_bilibili​