-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTest.java
More file actions
78 lines (48 loc) · 1.5 KB
/
Test.java
File metadata and controls
78 lines (48 loc) · 1.5 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package refrence;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
/**
* SoftReference 只有在堆内存不足时才回收SoftReference中的引用
* 无强引用时
* WeakReference 在垃圾收集器运行时回收WeakReference中的引用
* 无强引用,无软引用
* PhantomReference 不影响回收
* 无强引用,无软引用,无弱引用,没有重写finalize或者finalize已经运行
*/
public class Test {
private static final ReferenceQueue<E> queue = new ReferenceQueue<>();
private static WeakReference<E> wekRef;
private static SoftReference<E> softRef;
private static PhantomReference<E> phantomRef;
public static void main(String[] args) {
E instance = new E();
wekRef = new WeakReference<>(instance,queue);
softRef = new SoftReference<>(instance,queue);
phantomRef = new PhantomReference<>(instance,queue);
instance = null;
System.gc();
System.out.println("Start");
Reference<? extends Object> ref = null;
try {
while((ref = queue.remove()) != null) {
System.out.println(ref.getClass().getName());
if(ref instanceof PhantomReference) {
ref.clear();
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("End");
}
private static class E{
@Override
protected void finalize() throws Throwable {
super.finalize();
}
}
}