Garbage collection in Java is the process of managing memory, automatically. It finds the unused objects (that are no longer used by the program) and delete or remove them to free up the memory. The garbage collection mechanism uses several GC algorithms. The most popular algorithm that is used is Mark and Sweep.
Some of the advantages of garbage collection in Java are:
- - It makes Java memory efficient because garbage collector removes the unreferenced objects from heap memory.
- - It is automatically done by the garbage collector (a part of JVM) so we don't need to make extra efforts.
- - It prevents memory leaks and errors that may occur due to manual memory management.
Some of the important concepts related to garbage collection in Java are:
- - Unreachable objects: An object is said to be unreachable if it doesn’t contain any reference to it. Also, note that objects which are part of the island of isolation are also unreachable.
- - Eligibility for garbage collection: An object is said to be eligible for GC (garbage collection) if it is unreachable.
- - finalize() method: The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as: `protected void finalize() {}`.
- - gc() method: The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes. `public static void gc() {}`.
Here is a simple example of garbage collection in Java:
```java
public class TestGarbage1 {
public void finalize() {
System.out.println("object is garbage collected");
}
public static void main(String args[]) {
TestGarbage1 s1 = new TestGarbage1();
TestGarbage1 s2 = new TestGarbage1();
s1 = null;
s2 = null;
System.gc();
}
}
```
The output of this program will be:
```
object is garbage collected
object is garbage collected
```
This shows that the two objects created by s1 and s2 are eligible for garbage collection and are deleted by the garbage collector.