为断根一个对象,阿谁对象的用户必需在但愿进行断根的地址挪用一个断根体例。这听起来似乎很轻易做到,但饶暌闺C++“破损器”的概念稍有抵触。在C++中,所有对象城市破损。若但愿执行除释放存储空间之外的其他某种形式的断根工作,仍然必需挪用Java中的一个体例。它等价于C++的破损器,只是没后者便利。
. S4 l5 A" U% L* S0 R' H, M3 _ finalize()最有用处的处所之一是不雅察看垃收受接管集的过程。下面这个例子向巨匠展示了垃收受接管集所履历的过程,并对前面的陈述进行了总结。//: Garbage.java
# o6 d8 y& I: s) i // Demonstration of the garbage u) m6 m* h" B( d# L
// collector and finalizationclass Chair {
% J# r6 A5 G; [ static boolean gcrun = false;
' F, p' t. R% J% P! a# \ static boolean f = false;. M/ }7 Z" Y. T: ^
static int created = 0;
: I" M$ n ^4 o5 C static int finalized = 0;
3 g) S: ?1 t, g. N% d int i;
1 ~) a" A* Y/ c6 T# B R. b5 p& b' v Chair() {# a1 j# j' M" P9 L" s
i = ++created;" w6 L/ }# \7 C
if(created == 47)7 Z! Y+ C9 X& z4 }" t( q
System.out.println("Created 47");
( y- d# Z1 Z5 Y1 n1 x/ C }
( G" S5 Z! k1 H& m* R' C protected void finalize() {
; C+ ?7 m- o2 V if(!gcrun) {$ U5 O( |% f( }/ h/ ?/ e
gcrun = true;) X" ? d; @' q( F$ p
System.out.println(
1 ^% k2 a1 i, j- e% g7 { "Beginning to finalize after " +* d( w0 Q. u" r* f8 D
created + " Chairs have been created");5 ^8 @( ]- o/ O7 I
}
8 c7 H! r& [) v$ V4 b2 m if(i == 47) {4 N Y6 @7 m3 X7 S
System.out.println(
( P1 M0 e; [) P! ^* M) h$ k "Finalizing Chair #47, " +3 u( o9 l" b& O& |$ n
"Setting flag to stop Chair creation");
' H8 k/ H2 Z* z3 ~" d f = true;5 I* w# \/ O2 g4 ?/ h6 c" _
}
* C6 n, v3 j$ P5 s! e, \8 Z; d finalized++;8 @" u6 Q- Y- j6 x
if(finalized >= created)
E$ s3 @! ?( B9 C0 T7 C System.out.println(
$ w6 e' i" {" V+ k$ k6 X "All " + finalized + " finalized");
2 i8 Y. [* ^; a }
( B# w: }7 E& s* L2 B }public class Garbage {+ O6 ~4 n/ ]/ E$ [+ n
public static void main(String[] args) {
# @; e: o2 A. h' T4 ^2 D if(args.length == 0) {$ ~: s. x4 s4 l
System.err.println("Usage: n" +9 G* F: V+ ?' y: f' D Z6 X
"java Garbage beforenor:n" + ^) ?- L0 M$ \/ [. q
"java Garbage after");
' `7 E( ^( J& o2 k- `( G8 c$ x return;3 Z1 |1 k0 b9 X7 g" ?
}
2 m; d7 k( z/ h0 D& {% _& B: _$ ]( L while(!Chair.f) {6 |1 u6 @4 ?" f4 x% |
new Chair();
6 Y3 V& e- f1 i [ new String("To take up space");! r5 t- |; t! w V j3 `9 |; ^9 o3 }
} |