
本教程操作环境:windows7系统、java10版,DELL G3电脑。
1.概念
软引用是用来描述一些还有用,但非必须的对象。只被软引用关联着的对象,在系统将要发生内存溢出异常前,会把这些对象列进回收范围之中进行第二次回收,如果这次回收还没有足够的内存,才会抛出内存溢出异常
2.应用场景
软引用通常用来实现内存敏感的缓存。如果还有空闲内存,就可以暂时保留缓存,当内存不足时清理掉,这样就保证了使用缓存的同时,不会耗尽内存。
3.实例
byte[]data=newbyte[1*1024*1024];
ReferenceQueue<Object>referenceQueue=newReferenceQueue<>();
SoftReference<byte[]>softReference=newSoftReference<>(data,referenceQueue);
data=null;
System.out.println("before:"+softReference.get());
try{
for(inti=0;i<10;i++){
byte[]temp=newbyte[3*1024*1024];
System.out.println("processing:"+softReference.get());
}
}catch(Throwablet){
System.out.println("after:"+softReference.get());
t.printStackTrace();
}
while(referenceQueue.poll()!=null){
System.out.println("self:"+softReference);
softReference.clear();
softReference=null;
System.out.println("last:"+softReference);
}
VMoptions:-Xms5m-Xmx5m-XX:+PrintGC原文来自:https://www.py.cn © 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END


















































暂无评论内容