Garbage Collection in Java
Garbage collection is a crucial aspect of automatic memory management in programming languages like Java. Garbage collection in Java is about removing unused variables from the memory so that there is sufficient space for the new variables. Garbage collection works automatically in Java, making memory management more efficient. Garbage collection operates within the heap, the area of memory allocated to the Java Virtual Machine (JVM) for storing objects.
What is Garbage Collection?
Just like in our daily life we clean out homes, collect garbage, and dump it in dustbins, computer programs also require the cleaning of unused and garbage items. What happens if we don’t collect the garbage from our homes? It will create a mess and it will be difficult to find clean space to work or stay. In a similar context, if we don’t clean our running program, it will eat up the memory and make it difficult for us to maintain a healthy system. In computer languages, garbage is a variable that is no longer used. In this article, we will refer to the Garbage Collector as GC, a common term used in Java.
Many variables are created and kept in the memory when a program runs. With time, this count will keep increasing, and a time will come when the program will run out of memory and subsequently crash. In Java, we define this problem as OutOfMemoryError. We can also call this scenario a Memory Leak. We don’t want this, right? One solution is to have a massive RAM. But this is not a feasible solution. Let’s see how Java copes with this issue.
A garbage collector is a program that removes unwanted variables from memory. In C and C++, we do it manually by writing a method to handle this. But in Java, it is much easier. Java itself does the job for us in the background. A background thread running in Java keeps track of the objects that are eligible for removal from memory. We don’t even have to think of Garbage Collection in Java. Though Java does it, we need to have some control over it. Along with automatic garbage collection in Java, Java provides us with some features to configure when the GC should run or which type of GC to use.
How Does Garbage Collection Work in Java?
Java uses an automatic garbage collection system. The programmer does not need to explicitly indicate items for deletion.
The JVM houses the garbage collection implementation. Garbage collection can be implemented in different ways by each JVM. To deal with the objects in the heap memory, marking or identifying the unreachable objects and compaction them is required; it must adhere to the standard JVM specification.
GC runs in two phases to do the cleaning job. We call it Mark and Sweep. In the Mark step, GC “paints” the objects that are active, leaving the dead objects unmarked. The next Sweep step is performed where the GC looks for unpainted objects and collects them for removal from memory.
Types of Events in Java Garbage Collection
In Java, garbage collection events encompass two primary types:
-
Minor or Incremental Garbage Collection: This event occurs when the Java Virtual Machine (JVM) identifies and removes unreachable objects in the young generation heap memory. It focuses on reclaiming memory occupied by short-lived objects, thus ensuring efficient memory management.
-
Major or Full Garbage Collection: This event occurs when surviving objects from the minor garbage collection phase are transferred to the old or permanent generation heap memory. Unlike minor collections, the major collection addresses long-lived objects, making them less frequent but crucial for maintaining overall memory health.
Advantages of Garbage Collection in Java
The primary function of the Garbage collector is to automatically reclaim memory occupied by objects no longer in use or referenced by the program. This process helps prevent memory leaks and optimizes the utilization of memory resources. Some of the significant advantages of garbage collection in Java are mentioned below:
- Garbage collection in Java provides a crucial advantage by efficiently managing memory.
- Automatically removing unreferenced objects from the heap memory streamlines memory usage without requiring manual intervention.
- This automation, which the garbage collector handles as part of the JVM, simplifies memory management tasks, sparing developers from the need for additional efforts.
How Can an Object Be Unreferenced?
There are various methods for allowing Java's garbage collector to reclaim memory:
- Nullifying a reference
Here, we first create an object for a class and then assign null to it so that it becomes eligible for garbage collection.
- Assigning a reference to another
In this the reference of the original object is changed to another object and hence all the objects which are referenced by the first object become eligible for garbage collection.
- Using an anonymous object
These techniques facilitate the automatic memory management provided by Java's garbage collector, ensuring efficient memory usage in Java programs.
finalize() Method
The finalize() method in Java serves as a mechanism for performing cleanup operations on an object before it gets garbage collected. The finalize() method, present in the Object class, is called just before an object is garbage collected. It allows for cleanup operations to be executed, aiding in resource management. Its signature in the Object class is:
This method provides an opportunity to release any resources or perform any necessary cleanup tasks before the object is removed from memory. Due to its limitations and potential performance issues, the finalize() method has been deprecated in Java 9.
gc() Method
The gc() method in Java is a part of the System class and is used to suggest to the JVM (Java Virtual Machine) that it should run the garbage collector. The gc() method triggers the garbage collector to execute cleanup operations. However, it's important to note that calling gc() does not guarantee immediate garbage collection. This method is available in both the System and Runtime classes.
The Syntax for gc() method is declared as:
Real-World Example of Java Garbage Collection
Output:
Explanation: In this example, we have a class Main with a finalize() method that prints a message when garbage is collected from an object of this class. Inside the main method, we create two objects (obj1 and obj2) of the Main class, set them to null to make them eligible for garbage collection, and then explicitly call System.gc() to request garbage collection.
Note that the Java process's actual garbage collection is performed by the Java Virtual Machine (JVM), and the timing of when it runs is not guaranteed.
Conclusion
- In this article, we have seen the need for a Garbage Collector in Java.
- We also learned how Java runs and how to ask it to run whenever needed explicitly. It is worth noting that calling GC explicitly in code is unsuitable for application performance. Hence, we should avoid using it.
- Since the finalize() method is deprecated, we should use the Closeable interface wherever possible.
- Garbage collection helps mitigate the risk of memory leaks by automatically identifying and reclaiming memory associated with unreachable objects, preventing memory exhaustion over time.