java中四种引用类型
从JDK1.2开始,Java中的引用类型分为四种,分别是:
①强引用(StrongReference)
②软引用(SoftRefernce)
③弱引用(WeakReference)
④虚引用(PhantomReference)
Reference,引用表示存放的是另外一块内存的起始地址,引用指向某个对象
不同的引用类型对对象生命周期有影响,GC回收不一致
1,强引用(有用并且必需的)
当内存空间不足时,JVM宁可报错(OOM OutOfMemoryError内存溢出)也不会回收此引用引用着的对象空间(当方法没有执行完的时候)
2,软引用 (SoftRefernce 有用非必需)
当内存空间不足时,GC开始回收此类引用引用着的对象空间;如果空间充足不回收
public static void main(String[] args) {
int _1M = 1024 * 1024;
SoftReference<byte[]> by1 = new SoftReference<>(new byte[_1M * 3]);
System.out.println(by1.get().length);
SoftReference<byte[]> by2 = new SoftReference<>(new byte[_1M * 4]);
System.out.println(by1.get());
}
3,弱引用(WeakReference)(有用非必需)
弱引用引用着的对象活不到下一次GC,
public static void main(String[] args) {
int _1M = 1024 * 1024;
WeakReference<byte[]> by1 = new WeakReference<>(new byte[_1M * 3]);
System.out.println(by1.get().length);
WeakReference<byte[]> by2 = new WeakReference<>(new byte[_1M * 2]);
//通知GC开始回收
System.gc();
System.out.println(by1.get());
System.out.println(by2.get());
}
4,虚引用(PhantomReference)
虚引用主要用来跟踪对象被垃圾回收器回收的活动