强引用(可达性算法中描述的对象引用):GC Root对象跟普通对象有引用关系,只要这层关系存在,普通对象就不会被回收。除了强引用之外,Java中还有其他几种引用方式。
软引用:
相对于强引用是一种比较弱的引用关系。如果一个对象只有软引用关联到他,当内存不足时,就会将软引用中的数据进行回收。(强引用会保留)
SoftReference类实现软引用,软引用常用于缓存中。
SoftReference对象也需要被GC Root关联到否则软引用对象本身也会被回收。
上述代码运行结果为9。构造时传入软引用队列,最大堆内存分配为200。实际程序员可分配的只有100多,因为JVM会创建一些对象在堆上。在for循环中,每次创建100MB大小的数组,创建完将软引用放入软引用队列防止其被回收。第一次可正常创建,在第二次创建的是时候,发现内存不足,且上一次创建的只有软引用(for循环进入下一次后上一次已经无法访问,除非像软引用对象一样在循环外面创建数组,且将创建出来的放入数组,则不会被回收),于是删除上一次创建的。这样重复后直到最后一次,最后一次创建的未被回收。
在while循环中,不断将软引用队列中的软引用弹出来,前九次都能正常弹出,因为其软引用对象包含的对象已经被回收。最后一次没有正常回收。则count=9。
软引用的使用场景——缓存
让缓存框架具备内存不足时自动回收。
附上代码:
package chapter04.soft;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
/**
* 软引用案例4 - 学生信息的缓存
*/
public class StudentCache {
private static StudentCache cache = new StudentCache();
public static void main(String[] args) {
for (int i = 0; ; i++) {
StudentCache.getInstance().cacheStudent(new Student(i, String.valueOf(i)));
}
}
private Map<Integer, StudentRef> StudentRefs;// 用于Cache内容的存储
private ReferenceQueue<Student> q;// 垃圾Reference的队列
// 继承SoftReference,使得每一个实例都具有可识别的标识。
// 并且该标识与其在HashMap内的key相同。
private class StudentRef extends SoftReference<Student> {
private Integer _key = null;
public StudentRef(Student em, ReferenceQueue<Student> q) {
super(em, q);
_key = em.getId();
}
}
// 构建一个缓存器实例
private StudentCache() {
StudentRefs = new HashMap<Integer, StudentRef>();
q = new ReferenceQueue<Student>();
}
// 取得缓存器实例
public static StudentCache getInstance() {
return cache;
}
// 以软引用的方式对一个Student对象的实例进行引用并保存该引用
private void cacheStudent(Student em) {
cleanCache();// 清除垃圾引用
StudentRef ref = new StudentRef(em, q);
StudentRefs.put(em.getId(), ref);
System.out.println(StudentRefs.size());
}
// 依据所指定的ID号,重新获取相应Student对象的实例
public Student getStudent(Integer id) {
Student em = null;
// 缓存中是否有该Student实例的软引用,如果有,从软引用中取得。
if (StudentRefs.containsKey(id)) {
StudentRef ref = StudentRefs.get(id);
em = ref.get();
}
// 如果没有软引用,或者从软引用中得到的实例是null,重新构建一个实例,
// 并保存对这个新建实例的软引用
if (em == null) {
em = new Student(id, String.valueOf(id));
System.out.println("Retrieve From StudentInfoCenter. ID=" + id);
this.cacheStudent(em);
}
return em;
}
// 清除那些所软引用的Student对象已经被回收的StudentRef对象
private void cleanCache() {
StudentRef ref = null;
while ((ref = (StudentRef) q.poll()) != null) {
StudentRefs.remove(ref._key);
}
}
// // 清除Cache内的全部内容
// public void clearCache() {
// cleanCache();
// StudentRefs.clear();
// //System.gc();
// //System.runFinalization();
// }
}
class Student {
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}