-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGarbage.java
More file actions
77 lines (70 loc) · 1.59 KB
/
Garbage.java
File metadata and controls
77 lines (70 loc) · 1.59 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
package garbage;
/**
* 测试垃圾收集时finalize()方法被调用的情况
* 经测试发现有些对象的finalize()方法没有被调用
* @author Administrator
*
*/
public class Garbage{
static boolean stopCreate = false;
public static void main(String[] args) {
System.out.println(args[0]);
new Thread(){
public void run() {
try {
sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
stopCreate = true;
}
}.start();
while(!Chair.f && !stopCreate){
new Chair();
new String("To take up space");
}
System.out.println("After all Chairs have been created:\n"
+ "total created = " + Chair.created
+ ",total finalized = " + Chair.finalized);
if(args[0].equals("before")){
System.out.println("gc():");
System.gc();
System.out.println("runFinalizeation():");
System.runFinalization();
}
System.out.println("bye!");
if(args[0].equals("after")){
System.runFinalizersOnExit(true);
}
}
}
class Chair {
volatile static boolean gcrun;
volatile static boolean f;
volatile static int created = 0;
volatile static int finalized = 0;
int i;
Chair(){
i = ++ created;
if(created == 47){
System.out.println("Created 47");
}
}
@Override
protected void finalize(){
if(!gcrun){
gcrun = true;
}
System.out.println("Beginning to finlize " + i + " after "
+ created + " Chairs have been created");
if(i == 47){
System.out.println("Finalizing Chair #47, "
+ "Setting flag to stop Chair creation");
f = true;
}
finalized++;
if(finalized >= created){
System.out.println("All " + finalized + " finalized");
}
}
}