-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGarbageTest.java
48 lines (40 loc) · 1.18 KB
/
GarbageTest.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
/* Java program to demonstrate that
objects created inside a method will become
eligible for gc after method execution terminate */
/*How to make object eligible for garbage collection in Java? */
class GarbageTest
{
// to store object name
String obj_name;
public GarbageTest(String obj_name)
{
this.obj_name = obj_name;
}
static void show()
{
//object t1 inside method becomes unreachable when show() removed
GarbageTest t1 = new GarbageTest("t1");
display();
}
static void display()
{
//object t2 inside method becomes unreachable when display() removed
GarbageTest t2 = new GarbageTest("t2");
}
// Driver method
public static void main(String args[])
{
// calling show()
show();
// calling garbage collector
System.gc();
}
@Override
/* Overriding finalize method to check which object
is garbage collected */
protected void finalize() throws Throwable
{
// will print name of object
System.out.println(this.obj_name + " successfully garbage collected");
}
}