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