Garbage Collection Java Interview Questions – Set 02

Explain in depth Garbage collector ?

Garbage collection is the process of automatically freeing objects that are no longer referenced by the program. This frees the programmer from having to keep track of when to free allocated memory, thereby preventing many potential bugs. Thus making programmers more productive as they can now put more effort in coding rather than worrying about memory management.

The only disadvantage of garbage collector is it adds overheads. Because the JVM (Java virtual machine) has to keep a constant track of the objects which are not referenced and then free these unreferenced objects on fly. This whole process has a slight impact on the application performance. But garbage collector has a good algorithm and it runs in its own thread thus having a least impact on the application performance but still it has some impact.

What is Garbage Collection and how to call it explicitly?-

When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.

Does System.gc and Runtime.gc() guarantee garbage collection

No

Does garbage collection guarantee that a program will not run out of memory

Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

How can we force the garbage collector to run?

Garbage collector can be run forcibly using “System.gc()” or “Runtime.gc()”

What is finalize() method?-

finalize () method is used just before an object is destroyed and can be called just prior to garbage collection

How many times may an object’s finalize() method be invoked by the garbage collector?

An object’s finalize() method may only be invoked once by the garbage collector

If an object is garbage collected, can it become reachable again

Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.

Can an object’s finalize() method be invoked while it is reachable

An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects.

Explain Servlet Life Cycle

A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet

  • The servlet is initialized by calling the init ()
  • The servlet calls service()method to process a client’s request.
  • The servlet is terminated by calling the destroy()
  • Finally, servlet is garbage collected by the garbage collector of the JVM.