ReferenceQueue queue = new ReferenceQueue ();
PhantomReference pr = new PhantomReference (object, queue);
|
MyObject aRef = new MyObject();
SoftReference aSoftRef=new SoftReference(aRef);
|
aRef = null;
|
MyObject anotherRef=(MyObject)aSoftRef.get();
|
ReferenceQueue queue = new ReferenceQueue();
SoftReference ref=new SoftReference(aMyObject, queue);
|
SoftReference ref = null;
while ((ref = (EmployeeRef) q.poll()) != null) {
// 清除ref
}
|
public class Employee {
private String id;// 僱員的標識號碼
private String name;// 僱員姓名
private String department;// 該僱員所在部門
private String Phone;// 該僱員聯繫電話
private int salary;// 該僱員薪資
private String origin;// 該僱員信息的來源
// 構造方法
public Employee(String id) {
this.id = id;
getDataFromlnfoCenter();
}
// 到數據庫中取得僱員信息
private void getDataFromlnfoCenter() {
// 和數據庫建立連接井查詢該僱員的信息,將查詢結果賦值
// 給name,department,plone,salary等變量
// 同時將origin賦值爲"From DataBase"
}
……
|
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.Hashtable;
public class EmployeeCache {
static private EmployeeCache cache;// 一個Cache實例
private Hashtable<String,EmployeeRef> employeeRefs;// 用於Chche內容的存儲
private ReferenceQueue<Employee> q;// 垃圾Reference的隊列
// 繼承SoftReference,使得每一個實例都具有可識別的標識。
// 並且該標識與其在HashMap內的key相同。
private class EmployeeRef extends SoftReference<Employee> {
private String _key = "";
public EmployeeRef(Employee em, ReferenceQueue<Employee> q) {
super(em, q);
_key = em.getID();
}
}
// 構建一個緩存器實例
private EmployeeCache() {
employeeRefs = new Hashtable<String,EmployeeRef>();
q = new ReferenceQueue<Employee>();
}
// 取得緩存器實例
public static EmployeeCache getInstance() {
if (cache == null) {
cache = new EmployeeCache();
}
return cache;
}
// 以軟引用的方式對一個Employee對象的實例進行引用並保存該引用
private void cacheEmployee(Employee em) {
cleanCache();// 清除垃圾引用
EmployeeRef ref = new EmployeeRef(em, q);
employeeRefs.put(em.getID(), ref);
}
// 依據所指定的ID號,重新獲取相應Employee對象的實例
public Employee getEmployee(String ID) {
Employee em = null;
// 緩存中是否有該Employee實例的軟引用,如果有,從軟引用中取得。
if (employeeRefs.containsKey(ID)) {
EmployeeRef ref = (EmployeeRef) employeeRefs.get(ID);
em = (Employee) ref.get();
}
// 如果沒有軟引用,或者從軟引用中得到的實例是null,重新構建一個實例,
// 並保存對這個新建實例的軟引用
if (em == null) {
em = new Employee(ID);
System.out.println("Retrieve From EmployeeInfoCenter. ID=" + ID);
this.cacheEmployee(em);
}
return em;
}
// 清除那些所軟引用的Employee對象已經被回收的EmployeeRef對象
private void cleanCache() {
EmployeeRef ref = null;
while ((ref = (EmployeeRef) q.poll()) != null) {
employeeRefs.remove(ref._key);
}
}
|