java基础之软引用
软引用
软引用是指使用 SoftReference
如果一个对象只有软引用,内存充足时是不会对其进行回收的,只有当内存溢出时才会对其进行回收。JVM会尽可能优先回收闲置时间长的软引用,尽量保留新创建的软引用。可以通过get()方法获取软引用中的强引用。
demo
public class SoftReferenceTest {
public static void main(String[] args) {
// 软引用,为这个main方法分配一个 -Xmx10M的运行内存
SoftReference<byte[]> softReference = new SoftReference<>(new byte[1024*1024 * 6]);
// softReference=null;
// 软引用可以通过get()方法,获取到这个对象的强引用对象
System.out.println(softReference.get());
// 调用GC
System.gc();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(softReference.get());
// 再分配一个强引用,heap将装不下,这时候系统会回收,先回收一次,如果还不够,就会把软引用干掉
// byte[] bytes = new byte[1024 * 1024 * 6];
// 若还不够,则会内存溢出
// byte[] byte2 = new byte[1024 * 1024 * 12];
// 再分配一个弱引用,heap将装不下,这时候系统会回收,先回收一次,如果还不够,就会把软引用干掉
// SoftReference<byte[]> softReference2 = new SoftReference<>(new byte[1024*1024 * 6]);
// 若还不够,则会内存溢出
SoftReference<byte[]> softReference2 = new SoftReference<>(new byte[1024*1024 * 10]);
System.out.println(softReference.get());
System.out.println(softReference2.get());
}
}
应用场景
可以用来做缓存使用
本文来自博客园,作者:King-DA,转载请注明原文链接:https://www.cnblogs.com/qingmuchuanqi48/articles/17464973.html

浙公网安备 33010602011771号