What is Garbage Collection?
By System class: System class contains a static method GC for this.
By Runtime class : Runtime class is a singleton class present in java.lang. Package. We can create Runtime object by using factory method getRuntime().
Finalization:
Just before destroying any object gc always calls finalize() method to perform cleanup activities. Once finalize() method completes, Garbage Collector destroys that object.
finalize() method is present in Object class.
Memory leak:
An object which is not using in our application and it is not eligible for Garbage Collector such type of objects are called “memory leaks”.
Garbage Collector is the process of Java program which runs
in the background along with regular Java program to collect unused memory
space for improving the performance of our applications.
The ways to make an object eligible for Garbage Collector :
- Nullifying the reference variable
- Reassign the reference variable
- Objects created inside a method
· 1. Nullifying the reference variable :
If an object is no longer required then we can make eligible for Garbage Collector(GC) by assigning “null” to all its reference variables.
2.Reassign the reference variable :
·
If an object is no longer required then reassign all its
reference variables to some other objects then old object is by default eligible
for Garbage Collector(GC).
3.Objects created inside a method :
· Objects created inside a method are by default eligible for Garbage Collector(GC) once method completes.
Ways for requesting JVM to run Garbage Collector :
By System class: System class contains a static method GC for this.
Example: System.gc();
|
System.gc() method is used to call the garbage collector to perform clean-up processing.
By Runtime class : Runtime class is a singleton class present in java.lang. Package. We can create Runtime object by using factory method getRuntime().
Example: Runtime.getRuntime().gc();
|
Note : The System.gc() is effectively equivalent to the Runtime.getRuntime().gc().
Ques : Can the Garbage Collection be forced by any means?
Ans : No. The Garbage Collection can not be forced, though there are few ways by which it can be requested there is no guarantee that these requests will be taken care of by JVM.
Finalization:
Just before destroying any object gc always calls finalize() method to perform cleanup activities. Once finalize() method completes, Garbage Collector destroys that object.
protected void finalize() throws Throwable
|
Memory leak:
An object which is not using in our application and it is not eligible for Garbage Collector such type of objects are called “memory leaks”.
No comments:
Post a Comment