Subject not found.
1.

What is Garbage Collection in Java?

Answer»

Garbage collection is the PROCESS of examining heap MEMORY, DETERMINING which items are in use and which are not, and then eliminating the objects that aren't.

An in-use object, also known as a referenced object, signifies that it is still referenced by some portion of your program. An unreferenced object, also known as an unused object, is one that is no longer referenced by any portion of your program. An unreferenced object's memory can thus be reclaimed. The most significant benefit of garbage collection is that it relieves us of a load of manual memory allocation and deallocation, allowing us to focus on the problem at hand.

Once we've made an object garbage-collectable, the garbage collector won't be able to DESTROY it right away. Only the object is destroyed when JVM executes the Garbage Collector program. However, we cannot predict when JVM will execute the Garbage Collector. We can also ask JVM to run Garbage Collector on our behalf. It can be DONE in two ways:

  • Using the System.gc() method: The static method gc() in the System class is used to ask the JVM to launch the Garbage Collector.
  • Using the Runtime.getRuntime().gc() method: The Runtime class allows an application to communicate with the JVM it is executing on. As a result, we can ask JVM to run Garbage Collector by calling its gc() method.


Discussion

No Comment Found