File tree Expand file tree Collapse file tree 2 files changed +89
-0
lines changed
java-jvm/src/main/java/com/brianway/learning/java/jvm/gc Expand file tree Collapse file tree 2 files changed +89
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .brianway .learning .java .jvm .gc ;
2+
3+ /**
4+ * Created by brian on 17/3/3.
5+ * 对象可以在被 GC 时自我拯救
6+ * 这种自救的机会只有一次,因为一个对象的 finalize() 方法最多只会被系统自动调用一次
7+ */
8+ public class FinalizeEscapeGC {
9+ public static FinalizeEscapeGC SAVE_HOOK = null ;
10+
11+ public void isAlive () {
12+ System .out .println ("yes, i am still alive :)" );
13+ }
14+
15+ @ Override
16+ protected void finalize () throws Throwable {
17+ super .finalize ();
18+ System .out .println ("finalize method executed" );
19+ FinalizeEscapeGC .SAVE_HOOK = this ;
20+ }
21+
22+ public static void main (String [] args ) throws Throwable {
23+ SAVE_HOOK = new FinalizeEscapeGC ();
24+
25+ //对象第一次成功拯救自己
26+ SAVE_HOOK = null ;
27+ System .gc ();
28+
29+ // finalize 优先级低,暂停 0.5 秒以等待
30+ Thread .sleep (500 );
31+
32+ if (SAVE_HOOK != null ) {
33+ SAVE_HOOK .isAlive ();
34+ } else {
35+ System .out .println ("no, i ma dead :(" );
36+ }
37+
38+ //与上面完全相同,缺失败
39+ SAVE_HOOK = null ;
40+ System .gc ();
41+
42+ // finalize 优先级低,暂停 0.5 秒以等待
43+ Thread .sleep (500 );
44+
45+ if (SAVE_HOOK != null ) {
46+ SAVE_HOOK .isAlive ();
47+ } else {
48+ System .out .println ("no, i ma dead :(" );
49+ }
50+
51+ }
52+ }
53+
54+ /*
55+ finalize method executed
56+ yes, i am still alive :)
57+ no, i ma dead :(
58+ */
Original file line number Diff line number Diff line change 1+ package com .brianway .learning .java .jvm .gc ;
2+
3+ /**
4+ * Created by brian on 17/3/2.
5+ * 引用计数算法缺陷
6+ */
7+ public class ReferenceCountingGC {
8+ public Object instance = null ;
9+ private static final int _1MB = 1024 * 1024 ;
10+
11+ /**
12+ * 占点内存,以便 GC 日志观看
13+ */
14+ private byte [] bigSize = new byte [2 * _1MB ];
15+
16+ public static void main (String [] args ) {
17+ testGC ();
18+ }
19+
20+ public static void testGC () {
21+ ReferenceCountingGC objA = new ReferenceCountingGC ();
22+ ReferenceCountingGC objB = new ReferenceCountingGC ();
23+ objA .instance = objB ;
24+ objB .instance = objA ;
25+
26+ objA = null ;
27+ objB = null ;
28+
29+ System .gc ();
30+ }
31+ }
You can’t perform that action at this time.
0 commit comments