四种引用
强引用
Object object =new Object();
String str =“hello”;
强引用有引用变量指向时永远不会被垃圾回收,JVM宁愿抛出OutOfMemory错误也不会回收这种对象。
软引用
如果一个对象具有软引用,只有当内存空间不足了,才会回收这些对象的内存。只要垃圾回收器没有回收它,该对象就可以被程序使用。

主函数
class MyArray{
byte[] array = new byte[1024 * 1024 * 3];
}
public class SoftReferenceTest {
public static void main(String[] args) {
//引用队列:存储被GC回收的对象
ReferenceQueue<MyArray> queue = new ReferenceQueue<>();
//软引用的方式创建,w就是MyArray的软引用
SoftReference<MyArray> w = new SoftReference<>(new MyArray(),queue);
System.out.println("内存足够时:"+queue.poll());
//此处需要3M的内存,内存不够了,所以触发GC,回收软引用对象
byte[] array = new byte[1024 * 1024 * 3];
//软引用对象被回收后存到引用队列中
System.out.println("内存不够后:"+queue.poll());
}
}
结果
弱引用
只被弱引用关联的对象,当GC触发时,不管内存是否够用,都会回收。
主函数
public class WeakReferenceTest {
public static void main(String[] args) {
ReferenceQueue<MyArray> queue = new ReferenceQueue<>();
WeakReference<MyArray> w = new WeakReference<>(new MyArray(),queue);
System.out.println("内存足够时:"+queue.poll());
System.gc();//手动调用gc
System.out.println("调用gc后:"+queue.poll());
}
}
结果
虚引用
虚引用和前面的软引用、弱引用不同,它并不影响对象的生命周期。
如果一个对象与虚引用关联,则跟没有引用与之关联一样,在任何时候都可能被垃圾回收器回收。设置虚引用的目的是在这个对象被GC回收时收到一个系统通知。
主函数
public class PhantomReferenceTest {
public static void main(String[] args) {
ReferenceQueue<MyArray> queue = new ReferenceQueue<>();
//创建虚引用
PhantomReference<MyArray> w = new PhantomReference<>(new MyArray(),queue);
System.out.println(queue.poll());
System.gc();
try {
Thread.sleep(1000);//让gc充分发生
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(queue.poll());
}
}
结果
WeakHashMap
特点
存储的key都是弱引用。
继承的接口
public class WeakHashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>
其内部的Entry继承了WeakReference,也就是弱引用,所以就具有了弱引用的特点。ReferenceQueue的作用是GC会清理掉对象之后,引用对象会被放到ReferenceQueue中。
使用
public class WeakHashMapTest {
public static void main(String[] args) {
WeakHashMap<String,Integer> map = new WeakHashMap<>();
String str1 = new String("123");
String str2 = new String("456");
map.put(str1,100);map.put(str2,200);
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, Integer> next = iterator.next();
System.out.println("key:"+next.getKey()+" value:"+next.getValue());
}
str1 = null;//释放强引用
System.gc();
System.out.println("---------------------------");
Iterator<Map.Entry<String, Integer>> iterator1 = map.entrySet().iterator();
while(iterator1.hasNext()){
Map.Entry<String, Integer> next = iterator1.next();
System.out.println("key:"+next.getKey()+" value:"+next.getValue());
}
}
}
结果
总结
HashMap和WeakHashMap的不同之处?
- WeakHashMap不能使用clone方法,不能进行序列化。
- WeakHashMap存储数据时,如果key为空,会用Object对象替换null,实际上存储的是new Object();,但打印的还是null。
- WeakHashMap的key不能使用基础数据类型。