-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dog.java
61 lines (48 loc) · 1.82 KB
/
Dog.java
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
public class Dog {
private static Dog dogOfTheWeek = null;
private String name;
public void setAsDogOfTheWeek() {
dogOfTheWeek = this;
}
public static Dog getDogOfTheWeek() {
return dogOfTheWeek;
}
public Dog(String name) { this.name = name;}
public static void main(String [] args) {
Dog d1 = new Dog("Fido");
Dog d2 = new Dog("Rover");
Dog d3 = new Dog("Princess");
Dog d4 = new Dog("Spot");
Dog d5 = new Dog("Snoopy");
d1.setAsDogOfTheWeek(); gc();
d1 = d2; gc();
Dog d6 = d3; gc();
Dog temp = d4; gc();
d4 = d3; gc();
d3 = temp; gc();
d2 = getDogOfTheWeek(); gc();
d4.setAsDogOfTheWeek(); gc();
d5 = null; gc();
d4 = null; gc();
d3 = null; gc();
d2 = null; gc();
d1 = null; gc();
temp = null; gc();
}
// SEE: https://ucsb-cs56-pconrad.github.io/topics/java_gc_under_the_hood/
public void finalize() {
System.out.println("Finalizing: " + this.name + " " + this.hashCode());
}
public static void gc() {
// from http://stackoverflow.com/questions/1346391/line-equivalent-in-java
// unnecessary java.lang. prefix used just to show where StackTraceElement comes from
java.lang.StackTraceElement ste = Thread.currentThread().getStackTrace()[2];
String where =
ste.getClassName() + " " + ste.getMethodName() + " " + ste.getLineNumber() + " ";
System.out.println("Requesting gc at: " + where);
System.gc();
System.runFinalization ();
System.gc();
System.runFinalization ();
}
}