Java is a general-purpose programming language and if in case you come up with a situation where there are unused data in your program and you do not know how to handle it, Garbage Collection in Java comes in handy. So, I’m writing this article to help you out with handling these functions.
I’ll be covering the topics in the following order:
- What is Garbage Collection in Java?
- How does Garbage Collection work?
- Types of Garbage Collection
- Advantages
- Best Practices
Let’s get started!
What is Garbage Collection in Java?
In Java, programmers face the issue of having to destroy the objects that are out of use. But with the Garbage Collector, this can be easily taken care of. The main objective of this Garbage Collector is to free heap memory by destroying the objects doesn’t contain a reference. The technique is known as Garbage Collection.
It is also considered as a program that helps to perform automatic memory management. When Java programs are run on the JVM, objects are created on the heap, which is actually a portion of memory that is dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up some memory.
- Programs that do not de-allocate memory can eventually break when there is no memory left in the system to allocate. All these programs are said to have memory leaks.
- Garbage collection in Java happens automatically during the lifetime of a program, eliminating the necessity to de-allocate memory and therefore avoiding memory leaks.
- Methods like free() in C and delete() in C++ are used but, in Java, it is performed automatically. So, Java provides better memory management.
Now, let’s understand how this automatic garbage collection works in Java.
Note: An object is said to be eligible for garbage collection iff it is unreachable.
How does Garbage Collection work?
Garbage Collection is a process of working with the Heap memory and also mark or identify the unreachable objects and destroy them with compaction.
Garbage collection in Java is an automatic process and the programmer does not have to explicitly mark objects to be deleted. The implementation mainly lives in the JVM. Each JVM can implement garbage collection. The only requirement is that it should meet the JVM specification.
Even though there are many JVMs available, Oracle’s HotSpot is by far the most common as it offers a robust and mature set of garbage collection options.
- The HotSpot has several garbage collectors that are optimized for various use cases, and all the garbage collectors follow the same basic process.
- In the very first step, unreferenced objects are identified and marked as ready for garbage collection.
- In the second step, the marked objects are deleted. Optionally, memory can be compacted after the garbage collector deletes objects, so remaining objects are in a contiguous block at the start of the heap. The compaction process makes it easier to allocate memory to new objects sequentially after the block of memory allocated to existing objects.
All of HotSpot’s garbage collectors implement a generational collection strategy that categorizes objects by age. The rationale behind generational garbage collection is that most objects are short-lived and will be ready for garbage collection soon after creation.
Now let’s see what are the different types of garbage collectors.
Types of Garbage Collector
The JVM provides four different garbage collectors, all of them generational. Each one has its own advantages and limitations. The choice of which garbage collector to use lies with the user and there can be numerous differences in the throughput and application pauses.
There are namely 4 types of garbage collectors.
- Serial Garbage Collector (GC): All the garbage collection events are conducted serially in one single thread. Compaction is executed after each garbage collection.
- Parallel/throughput GC: Multiple threads are used for minor/small garbage collection. A single thread is used for major garbage collection and Old Generation compaction. Also, the Parallel variant uses multiple threads for major garbage collection and Old Generation compaction.
- CMS Collector: Multiple threads are used for small/minor garbage collection using the same algorithm as Parallel. Majority of the garbage collection is multi-threaded, but CMS runs concurrently along with the application processes to minimize application events. No compaction is performed.
- G1 Collector: This garbage collector is basically intended as a replacement for CMS. It is parallel and concurrent like CMS, but it works quite differently when it is compared to the older garbage collectors.
Let’s understand the advantages of Garbage collection in Java.
Advantages
- The biggest benefit of Java garbage collection is that it automatically handles the deletion of unused objects or some objects that are inaccessible to free up memory resources.
- Garbage Collection is now a new standard component of many popular programming languages.
- It makes Java memory-efficient. It is because the garbage collector removes the unreferenced objects from heap memory.
- It is automatically done by the garbage collector which is a part of JVM.
Best Practices
The best approach to adapt to Java garbage collection is by setting flags on the JVM. Flags have the ability to adjust the garbage collector to be used. It helps in making it the best suited for backend processing where long pauses for garbage collection are acceptable.
Another thing to note here is, the CMS garbage collector is designed to minimize pauses which makes it ideal for GUI applications where responsiveness is highly important. Additional fine-tuning can be accomplished by changing the size of the heap or its sections and measuring garbage collection efficiency.
Let’s take a look at this program.
class Edureka { int a; int b; public void setData(int c,int d) { a=c; b=d; } public void showData() { System.out.println("Value of a = "+a); System.out.println("Value of b = "+b); } public static void main(String args[]) { Edureka e1 = new Edureka(); Edureka e2 = new Edureka(); e1.setData(1,2); e2.setData(3,4); e1.showData(); e2.showData(); //Edureka e3; //e3=e2; //e3.showData(); //e2=null; //e3.showData(); //e3=null; //e3.showData(); } }
In this case, the two objects and two reference variables are created. If you add another command e3=Null, two reference variables will point to the same object. And if there is no reference to the variable, e3=e2;e3.showData();At this point, there are no references pointing to the object and it becomes eligible for garbage collection.
This brings us to the end of this ‘Garbage Collection in Java’ article. We have learned how to remove unused objects in the heap and the different types of collection.
If you found this article on “Garbage Collection in Java”, check out the Java Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer.
Got a question for us? Please mention it in the comments section of this “Garbage Collection in Java” and we will get back to you as soon as possible.