Java Garbage Collection Interview Questions

Q1) Which part of the memory is involved in Garbage Collection? Stack or Heap?
Ans) Heap
Q2)What is responsiblity of Garbage Collector?
Ans) Garbage collector frees the memory occupied by the unreachable objects during the java program by deleting these unreachable objects.
It ensures that the available memory will be used efficiently, but does not guarantee that there will be sufficient memory for the program to run.
Q3) Is garbage collector a dameon thread?
Ans) Yes GC is a dameon thread. A dameon thread runs behind the application. It is started by JVM. The thread stops when all non-dameon threads stop.
Q4)Garbage Collector is controlled by whom?
Ans) The JVM controls the Garbage Collector; it decides when to run the Garbage Collector. JVM runs the Garbage Collector when it realizes that the memory is running low, but this behavior of jvm can not be guaranteed.
One can request the Garbage Collection to happen from within the java program but there is no guarantee that this request will be taken care of by jvm.
Q5) When does an object become eligible for garbage collection?
Ans) An object becomes eligible for Garbage Collection when no live thread can access it.
Q6) Can the Garbage Collection be forced by any means?
Ans) No. The Garbage Collection can not be forced, though there are few ways by which it can be requested there is no guarantee that these requests will be taken care of by JVM.
Q7) How can the Garbage Collection be requested?
Ans) There are two ways in which we can request the jvm to execute the Garbage Collection.
  • 1) The methods to perform the garbage collections are present in the Runtime class provided by java. The Runtime class is a Singleton for each java main program.
    The method getRuntime() returns a singleton instance of the Runtime class. The method gc() can be invoked using this instance of Runtime to request the garbage collection.
  • 2) Call the System class System.gc() method which will request the jvm to perform GC.
Q8) What is the purpose of overriding finalize() method?
Ans) The finalize() method should be overridden for an object to include the clean up code or to dispose of the system resources that should to be done before the object is garbage collected.

No comments:

Post a Comment

Please Provide your feedback here