forked from janzolau1987/study-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRefTest.java
More file actions
48 lines (45 loc) · 1.33 KB
/
RefTest.java
File metadata and controls
48 lines (45 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.yaoyaohao.study.reference;
import java.util.WeakHashMap;
/**
* 弱引用相关测试
*
* @author liujianzhu
* @date 2016年5月13日 下午5:25:47
*
*/
class KeyHolder {
@Override
protected void finalize() throws Throwable {
System.out.println("I am over from key");
super.finalize();
}
}
class ValueHolder {
@Override
protected void finalize() throws Throwable {
System.out.println("I am over from value");
super.finalize();
}
}
public class RefTest {
public static void main(String[] args) {
WeakHashMap<KeyHolder, ValueHolder> weakMap = new WeakHashMap<KeyHolder, ValueHolder>();
KeyHolder kh = new KeyHolder();
ValueHolder vh = new ValueHolder();
weakMap.put(kh, vh);
while (true) {
for (KeyHolder key : weakMap.keySet()) {
System.out.println(key + " : " + weakMap.get(key));
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("here...");
//这里把kh设为null,这样一来就只有弱引用指向kh指向的对象
kh = null;
System.gc();
}
}
}