为断根一个对象,阿谁对象的用户必需在但愿进行断根的地址挪用一个断根体例。这听起来似乎很轻易做到,但饶暌闺C++“破损器”的概念稍有抵触。在C++中,所有对象城市破损。若但愿执行除释放存储空间之外的其他某种形式的断根工作,仍然必需挪用Java中的一个体例。它等价于C++的破损器,只是没后者便利。
7 r" F/ o; q) r4 |- A& H finalize()最有用处的处所之一是不雅察看垃收受接管集的过程。下面这个例子向巨匠展示了垃收受接管集所履历的过程,并对前面的陈述进行了总结。//: Garbage.java9 A/ c# P" z* j, K8 J& ^2 J' H7 J
// Demonstration of the garbage& o' \8 m2 j' x5 P% E2 O8 f/ I
// collector and finalizationclass Chair {+ L) j9 }& V: c8 ^8 r+ R; h3 ~
static boolean gcrun = false;
1 B* k: \$ h7 d8 I) D# }7 I3 k static boolean f = false;% G0 x( d! k7 {* v! C
static int created = 0;2 D- @& z. @2 j8 s$ l5 y
static int finalized = 0;+ i# e4 w( }! w
int i;: S" n4 g t; l: s" ^
Chair() {
# E* ~0 w$ H2 x2 o+ W5 O i = ++created;
. N! Y/ k% \; S" ~0 ?8 P if(created == 47)
8 @3 Z9 k9 e( b1 l* I a# o2 r System.out.println("Created 47");6 w, s& u7 A9 ~3 V$ q# F
}/ n9 x; }0 ]8 a8 T9 t( h) z
protected void finalize() {& |- U/ e3 r* K8 K5 I& y- r
if(!gcrun) {) r; l/ R$ O! V4 B
gcrun = true;3 k4 C1 f# ~% j0 _2 @' `
System.out.println(
: \. V) L* \. I; w& y% D "Beginning to finalize after " +
; N0 s( q! q; h# X created + " Chairs have been created");
0 w) t8 }* d+ x0 ]. _2 Q; ] }* D' U0 b9 y0 C( W. q
if(i == 47) {
# V% B$ d$ [: N8 s+ x$ T0 j5 \ System.out.println() m% C+ |3 ~$ _& L* q; T/ e
"Finalizing Chair #47, " +( X# L0 d0 E% i3 C" P" i
"Setting flag to stop Chair creation");1 v8 T* N) s& K2 T
f = true;8 Z4 Z- I S7 a
}
) \1 S* }" u* c! {9 M finalized++;- }- B4 a+ t% \, V3 p2 b+ P6 G
if(finalized >= created)3 p2 L0 ?2 k; w9 L
System.out.println() q& x) S' H: [$ H$ u
"All " + finalized + " finalized");
+ V; L$ s, b5 b3 T- z }
% g9 Y' S5 G! o+ k- x }public class Garbage {/ h, t0 D* G6 _4 [' C: y/ g. Z+ a
public static void main(String[] args) {: [. x3 ]6 s# w' n
if(args.length == 0) {0 B6 h( R/ ?5 a6 t. k5 x
System.err.println("Usage: n" ++ `. P7 {2 a. d9 D8 F4 ^
"java Garbage beforenor:n" +% Z5 V0 l ~; y% ?2 t* i
"java Garbage after");
& n* D& s. ^! x2 ~# T2 Q5 W0 Y return;3 n7 v) {+ }6 ~0 S
}0 N+ y# k3 ^# C x+ ?
while(!Chair.f) {3 v! z* V# u0 N; m% w: h) @' G
new Chair();
7 q2 J+ ^' D4 T6 V$ s6 {* o) P5 k new String("To take up space");8 ]0 V& W5 S! {. w" C5 Z5 Q$ ^
}& e8 Y9 F! ~3 o
System.out.println(% g$ k, H+ t/ i! F1 q
"After all Chairs have been created:n" +( t4 d! `# ]$ ^
"total created = " + Chair.created +
& W2 X, a2 M! F: U& k ", total finalized = " + Chair.finalized);( {) B% y: H6 O# e7 O4 C6 P; t0 C2 y
if(args[0].equals("before")) {9 [6 o2 ?, @5 f: d' {' G% e) X- V
System.out.println("gc():");$ r- ^# E2 d# ?5 g% C2 M) a* a
System.gc();
$ r( U) [, V& E System.out.println("runFinalization():");5 T- c7 a' Y7 Y+ V/ [2 ]
System.runFinalization();" ^3 a3 }; Z7 K/ o
}$ s; o3 L2 }( j7 c5 ~- B, F
System.out.println("bye!");* r3 M, k' Q$ B3 P3 E; I- w- N
if(args[0].equals("after"))# C* q D/ U& P7 H
System.runFinalizersOnExit(true); |