Java garbage collector

Explain Java Garbage collector. Why garbage collection? Brief explanation of Garbage collection algorithms.

1. Garbage collection is the process of reclaiming heap memory space by removing orphan objects.
2. The objects that are no longer needed by the application are garbage collected.
3. Garbage collection is done automatically.

Need of garbage collection

1. Burden of reclaiming memory space is relieved by Garbage collection.
2. Flexibility to free the memory space explicitly.
3. Helps in ensuring program integrity.
4. Accidental crashing of JVM by incorrectly freeing memory is avoided by garbage collection.

Garbage Collection Algorithms

1. A garbage collection algorithm must detect the orphan objects.
2. A garbage collection algorithm must reclaim the heap space utilized by orphan objects. This reclaimed memory space is available again to the application.
3. The tracing garbage collectors will perform the garbage collection in the form of cycles.
4. The cycle is started when the garbage collector decides to reclaim the heap memory.
5. Entire memory set is touched several times by a method known as mark-and-sweep.

Explain the importance of finalizers in Java. Write code to depict the uses of finalizers in Java.

1. A finalizer is a method that performs finalization tasks for an object before it is garbage collected.

2. Cleanup tasks on an object or to release certain system resources like socket connections when the object is no longer needed.

3. The method finalize() of java.lang.Object is a finalizer.

4. The signature of finalizer is:
protected void finalize() throws Throwable

5. The objects that implement the finalize() method are often known as finalizable objects

6. The java garbage collector appends the orphan objects to a queue for finalization process

7. A special thread by name “Reference Handler” is performed by some JVMs

Code for finalizer method
protected void finalize() throws Throwable
{
   try
   {
      close();
   }
   catch(Exception e)
   {
      finally
      {
         super.finalize();
         //more code can be authored as per the application’s need
      }
   }
}
Java super keyword
Importance of 'super' keyword in Java - The keyword ‘super’ is used for referring parent class instance...
Java method overloading and overriding
Java method overloading and overriding - Define Method overloading, Uses of method overloading, uses of method overriding, Difference between overloading and overriding...
Java string class
Java string class - Describe Java string class. Explain methods of Java string class. Explain the characteristics of StringBuffer class.....
Post your comment