Java从JDK1.2版本开始,就把对象的引用分为四种级别,从而使程序能更加灵活的控制对象的生命周期。这四种级别由高到低依次为:强引用、软引用、弱引用和虚引用。本文给大家介绍Android利用软引用和弱引用避免OOM
他们的主要区别
引用 | 区别 |
---|---|
强引用 | 垃圾回收器绝对不会回收,即使抛出OutOfMemoryError错误,使程序异常终止 |
软引用 | 如果内存空间足够,垃圾回收器不会回收,如果内存空间不足,垃圾回收器会回收对象的内存 |
弱引用 | 不论内存是否足够,垃圾回收器都会回收对象的内存 |
虚引用 | 如果一个对象仅仅有虚引用,那它和没有任何引用一样。 |
强引用
//强引用(StrongReference)
//我们平时申明变量使用的就是强引用
public class MyStrongReference {
public static void main(String[] args) {
//创建强引用对象
String s1 = "test";
String s2 = "";
String s3 = null;
}
}
软引用
import java.lang.ref.SoftReference;
//软引用(SoftReference)
//当内存充足时,不会回收对象;当内存不足时,垃圾回收器会回收对象内存
public class MySoftReference {
public static void main(String[] args) {
String s1 = "test";
String s2 = "";
String s3 = null;
// 创建软引用对象
SoftReference<String> sr1 = new SoftReference<String>(s1);
SoftReference<String> sr2 = new SoftReference<String>(s2);
SoftReference<String> sr3 = new SoftReference<String>(s3);
}
}
弱引用
import java.lang.ref.WeakReference;
//弱引用(WeakReference)
//当垃圾回收器扫描到该对象,会进行回收
public class MyWeakReference {
public static void main(String[] args) {
String s1 = "test";
String s2 = "";
String s3 = null;
// 创建弱引用对象WeakHashMap
WeakReference<String> sr1 = new WeakReference<String>(s1);
WeakReference<String> sr2 = new WeakReference<String>(s2);
WeakReference<String> sr3 = new WeakReference<String>(s3);
}
}
虚引用
import java.lang.ref.PhantomReference;
//虚引用(PhantomReference)
//和没有任何引用一样
public class MyPhantomReference {
public static void main(String[] args) {
String s1 = "test";
String s2 = "";
String s3 = null;
// 创建虚引用对象WeakHashMap
PhantomReference<String> sr1 = new PhantomReference<String>(s1, null);
PhantomReference<String> sr2 = new PhantomReference<String>(s2, null);
PhantomReference<String> sr3 = new PhantomReference<String>(s3, null);
}
}