In this article, we are going to discuss Garbage Collection in java and the Advantages of Garbage Collection in java.
- Advantages of Garbage Collection in java.
- The ways to make an object eligible for GC
- The methods for requesting JVM to run GC
- Finalization
- We can discuss all method for calling GC
This topic is very important because in every interview some questions are coming related to this topic.
Introduction:
In old languages like C/C++ programmer is responsible for both the creation and destruction of objects. Usually, programmers are taking very much care while creating objects and neglect the destruction of useless objects.
Due to his negligence at a certain point of time for the creation of a new object if sufficient memory may not be
available and then the entire application may be crashed or terminate abnormally due to fewer memory problems.
But in java programmer is responsible only for the creation of the new object and he’s not responsible for the destruction of objects. For the destruction of useless objects, Sun people provided one assistant which is always running in the background, so programmers no need to worry about the destruction of useless objects.
That background assistant is nothing but a garbage collector.
Hence the main objective of a garbage collector is to destroy useless objects. So, java provides better memory management.
The best example of a Garbage collector is the Daemon thread as it is always running in the background.
Advantage of Garbage Collection:
The biggest advantage of Java GC is that it automatically handles the destruction of not required objects or objects
that are out of reach to free up vital memory resources, so we don’t need to make extra efforts.
It makes java memory-efficient because the garbage collector removes the unreferenced objects from heap memory.
The ways to make an object eligible for GC:
Even though the Programmer is not responsible for the destruction of objects, but good programming practice is always to make an object eligible for garbage collection if it is a useless object.
An object is eligible for useless objects if and only if it does not have any references.
The following are various possible ways to make an object eligible for GC:
- Nullifying the reference variable
- Re-assigning the reference variable
- An object created inside the method
- Island of Isolation
The methods for requesting JVM to run GC:
Once we made an object eligible for GC it may not be destroyed immediately by the garbage collection. Whenever JVM runs GC then only the object will be destroyed by the GC. But when exactly JVM runs garbage collector we can’t expert it is vendor dependent.
We can request JVM to run garbage collector programmatically, but whether JVM accepts our request or not there is no guaranty. But most of the time JVM will accept our request.
The following are various ways for requesting JVM to run GC:
By System class – (System.gc() method):
System class contains static method gc() for requesting JVM to run Garbage Collector.
Example:
System.gc();
By Runtime class -(Runtime.getRuntime().gc() method ):
- A java application can communicate with JVM by using Runtime object.
- Runtime class is a singleton class present in java.lang. Package.
- We can create a Runtime object by using the factory method getRuntime().
Example:
Runtime r=Runtime.getRuntime();
We can call the following methods on Runtime object.
freeMemory() : -> Using freeMemory() method we can returns the free memory present in the heap.
totalMemory() -> Using freeMemory() method we can returns total memory of the heap.
gc() -> Using freeMemory() method we can requesting jvm to run gc.
package com.technicalround.demo; import java.util.Date; class Demo { public static void main(String args[]) { Runtime rt = Runtime.getRuntime(); System.out.println("Total memory of the heap :" + rt.totalMemory()); System.out.println("Free memory of the heap :" + rt.freeMemory()); for (int i = 0; i < 10000; i++) { Date date = new Date(); date= null; } System.out.println("Free memory of the heap :" + rt.freeMemory()); rt.gc(); System.out.println("Free memory of the heap :" + rt.freeMemory()); } }
Output:
Total memory of the heap: 5177344
Free memory of the heap: 4994920
Free memory of the heap: 4743408
Free memory of the heap: 5049776
Valid ways for requesting JVM to run GC :
System.gc(); -> This method is valid.
Runtime.gc(); -> This method is invalid.
(new Runtime).gc(); -> This method is invalid.
Runtime.getRuntime().gc(); -> This method is valid.
Notes:
- gc() method present in System class is static, whereas it is the instance method in Runtime class.
- Over Runtime class gc() method, System class gc() method is recommended to use.
- In java, we are not able to find the size of an object and the address of an object.
Finalization:
Just before destroying any object Garbage Collector always calls the finalize() method to perform cleanup activities.
If the corresponding class contains the finalize() method then it will be executed otherwise Object class finalize() method will be executed.
Once the finalize() method completes, Garbage Collector destroys that object. It is present in the Object class.
Which is declared as follows.
protected void finalize() throws Throwable
Case 1:
Just before destroying any object, GC calls the finalize() method on the object which is eligible for GC then the corresponding class finalize() method will be executed.
For Example when the String object is eligible for GC then the String class finalize()method is
executed but not GCDemo1 class finalize()method.
package com.technicalround.demo; class GCDemo1 { public static void main(String args[]) { String s = new String("Niraj"); GCDemo1 gc = new GCDemo1(); s = null; System.gc(); System.out.println("End of main."); } public void finalize() { System.out.println("Finalize() method is executed"); } }
Output:
End of main.
In the above program actually String class finalize()method not executed. Because it is an empty implementation.
When we replace the String object with the GCDemo1 object then the GCDemo1 class finalize() method will be executed Please check the below example.
package com.technicalround.demo; class GCDemo2 { public static void main(String args[]) { String s = new String("Niraj"); GCDemo2 gcDemo = new GCDemo2(); gcDemo = null; System.gc(); System.out.println("End of main."); } public void finalize() { System.out.println("Finalize() method is executed"); } } Output: finalize() method is executed End of main
Read More topics related to the collection.
- Comparable and Comparator in Java
- Java Set Interface
- Java Vector
- Cursors in Java
- Collection Interface
- Collections in java
Read more topics related to java
- Multithreading in java
- Inter thread communication in java
- synchronization in java
- Exception in java
- Inner class in java
Hope this was helpful for you. If you have any questions please feel free to leave a comment. Thank you for reading.