JAVA四种引用

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);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值