Garbage collection is the process of automatically freeing memory on the heap by removing objects that are no longer reachable in your code.
System.gc()
is not guaranteed to run.
Java has a method called System.gc() to suggest a good time to start a garbage collection run.
Java virtual machine can ignore the request.
An object will remain on the heap until it is no longer reachable.
An object is no longer reachable when one of two situations occurs:
The reference is a variable which can be used to access the contents of an object.
A reference can be assigned to another reference, passed to a method, or returned from a method.
All references are the same size, no matter what their type is.
An object is on the heap and does not have a name.
Reference is the only way to access an object.
Objects have various sizes of memory.
It is the object that gets garbage collected, not its reference.
In the following code two String type variables are created first.
Then it uses the new to create two objects.
After that it assign the two
to one
. At this moment "a" is eligible to get garbage
collected since "a" is not pointed by any reference.
public class Main { public static void main(String[] args) { String one, two; one = new String("a"); two = new String("b"); one = two; String three = one; one = null; } }
Java allows objects to implement a method called finalize() that might get called.
finalize() method gets called if the garbage collector tries to collect the object.
If the garbage collector doesn't run, the method doesn't get called.
If the garbage collector fails to collect the object and tries to run it again, the method doesn't get called in the second time.
In practice, you are highly unlikely to use it in real projects.
Just keep in mind that it might not get called and that it definitely won't be called twice. The finalize() method could run zero or one time.
In the following code, finalize() method produces no output when we run it since the program exits before there is any need to run the garbage collector.
public class Main { protected void finalize() { System.out.println("Calling finalize"); } public static void main(String[] args) { Main f = new Main(); } }