Updated March 17, 2023
What is Java Garbage Collector?
The garbage collector is a daemon thread that frees memory during runtime. Garbage collection can also be expressed as memory recycling. Mostly in JVM, an oracle hotspot garbage collector is used due to its efficiency. The memory area in JVM where objects are created is called the heap. Heap is divided into two parts:
- Young generation space
- Old/tenured generation space
The young generation is again divided into 3 parts
- Eden space
- Survivor From
- Survivor To
A more deep explanation has been given in the next points. For example, if you created a cache in your program and if the cache object survived many cycles of GC, then it goes into the old generation. The GC looks for objects which are no longer needed by the program and destroys them.
Why Garbage Collector?
Before Java, two of the most popular languages were C and C++. In C, we have come across calloc(), malloc(), realloc() that will allocate buffer memory, and in C++, we have destructors. All these functions are for the feature called memory management. Java provides Garbage collector as automatic memory management for the main two reasons:
- First, some objects created become unreachable.
- Second, references from old objects to young objects only exist in small numbers.
Therefore, the best practice to use a garbage collector is to set flags on JVM.
Let me give you an example of unreachable objects.
//class code
int i = 1;
if(i == 1){
String s = abc;
System.out.println(s);
}
//class code
In the above example, Java will create a string object, and the scope of that object is just in that if the block cannot be used outside. Thus, when garbage collection runs over this class, it will mark ‘s’ as unreachable and unused object and will delete them.
Functions in Garbage Collector
- Mark: Starts from the root node of your application(main), walks the object graph, marks objects that are reachable as life.
- Delete/ Sweep: Delete unreachable objects. When GC deletes objects, it creates a hole in the heap, making it inconsistent. Thus, compaction is used.
- Compacting: Compact the memory by moving around the objects and marking the allocation contiguous than fragmented. It is a time-consuming task.
How does Java Garbage Collector work?
- There are two types of object:
Live Objects: Reachable (references from another object)
Dead Objects: Unreachable (not referenced from anywhere)
- All the newly created objects are created in the Eden space(Young Generation space).
- Once the Eden space is full, a minorGC() program runs on Young Generation space which marks all the unused or dead objects and sweeps them from memory.
- The objects which survived this GC cycle will be moved to Survivor From space. The same process repeats, and this time when objects are moved from Eden space to Survivor From space, GC checks whether it’s full, the dead objects are released, and survived objects will be moved to Survivor too.
- This process is repeated, and if some objects survived a threshold no of GC cycles, those objects are moved to Old Generation space.
- In this scenario, JVM runs the majorGC() function, which runs through complete heap space, identifies/marks unused(null or dead) objects and sweeps all these objects.
- Remember, sweeping objects from heap space will create holes in memory, causing a memory leak. To avoid such a scenario, the Garbage collector implements compaction of memory space.
Examples of Garbage Collector in Java
Example of system.gc():
class Demo {
public void finalize(){
System.out.println("Object");
}
public static void main(String args[]){
Demo obj1 = new Demo();
Demo obj2 = new Demo();
obj1 = null;
obj2 = null;
System.gc();
}
}
Output:
Explanation of the above code
- The above code, the two objects obj1 and obj2, are pointing to null, so they are stored in Eden space with null and unreferenced values.
- System gc() will invoke a daemon thread of garbage collection, and both the objects are deleted from the space.
Prons and cons
Below are some pros and cons of Java Garbage Collector as follows:
Pros of Garbage Collector:
- Garbage collection increases memory efficiency as it will delete all the unused and null objects.
- A garbage collector is an automatic process, so the developer may not take care of it because in other languages, without a garbage collector programmer has to take care of elusive memory problem.
Cons of Garbage Collector:
- The garbage collector will run a major gc function which will run through the entire heap space, making your program speed slowly by some seconds.
- This process will take more CPU time, making the code system slower.
- If you are working on an application requiring huge memory, make use of the JVM flags available.
- If heap space is full and objects cannot be swiped or added further, then Java throws out of Memory Error which will slow down the entire application and also can cause memory leaks.
Recommended Articles
This is a guide to What is Java Garbage Collector?. Here we discuss its working along with Functions, example, pros, and cons of Java garbage collector. You may also look at the following articles to learn more–