In C and C++, a programmer must manually invoke free()
and delete()
respectively to destroy or free up dynamically allocated memory for more objects. We don’t need to do this in Java, as it is done automatically using garbage collection.
The Java Runtime Environment (JRE) performs this task itself, which is known as garbage collection. Although we can manually include the method gc()
to observe how garbage collection works in Java, this is optional.
Usually, programmers come up with two types of garbage in a code.
A good tester or developer knows how to review the code manually. While reviewing, a programmer can tell that this specific code will lead to garbage at some point and occupy unnecessary memory. We can then sort it out at that exact moment.
Sometimes the programmer is unable to determine whether or a particular line of code will lead to garbage. We observe such code at runtime execution.
Garbage collection is beneficial because it reduces a programmer’s workload and increases the efficiency of the project.
Some more advantages of garbage collection include:
gc()
methodWe can invoke a garbage collector in our program using the built-in method gc().
The gc()
method performs cleanup of code and releases unnecessary occupied memory.
Although garbage collection in Java works automatically, there are still places where we must indicate the compiler to activate the garbage collector.
In other words, we must make the code eligible to perform garbage collection.
An object in Java only becomes eligible if it is unreachable (i.e., an object loses its value and points towards a null location).
Like before, we can manually use the garbage collector to learn how it works and acts in different conditions.
Let’s observe the below implementation of the garbage collector in Java.
class GarbageCollector {public static void main( String args[] ) {GarbageCollector gc1 = new GarbageCollector();// requesting Java garabage collectorSystem.gc();}}
The above piece of code implements a simple class, GarbageCollector
, that includes a dynamically allocated object named gc1
of the same class.
We invoked the System.gc()
method to run the garbage collector. The program returns no output, but shows that the execution is successful.
Free Resources