Java Garbage Collection Interview Questions
1 Explain Garbage collection in Java?
Ans: In Java, Garbage Collection is automatic. Garbage Collector Thread runs as a low priority daemon thread freeing memory.
2 When does the Garbage Collection happen?
Ans: When there is not enough memory. Or when the daemon GC thread gets a chance to run.
3 When is an Object eligible for Garbage collection?
Ans: An Object is eligible for GC, when there are no references to the object.
4 what are two steps in Garbage Collection?
Ans: 1. Detection of garbage collectible objects and marking them for garbage collection.
2. Freeing the memory of objects marked for GC.
5 what is the purpose of finalization?
Ans: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
6 Can GC be forced in Java?
Ans: No. GC can’t be forced.
7 what does System.gc () and Runtime.gc () methods do?
Ans: These methods inform the JVM to run GC but this is only a request to the JVM but it is up to the JVM to run GC immediately or run it when it gets time.
8 When is the finalize () called?
Ans: finalize () method is called by the GC just before releasing the object’s memory. It is normally advised to release resources held by the object in finalize () method.
9 Can an object be resurrected after it is marked for garbage collection?
Ans: Yes. It can be done in finalize () method of the object but it is not advisable to do so.
10 Will the finalize () method run on the resurrected object?
Ans: No. finalize () method will run only once for an object. The resurrected objects will not be cleared till the JVM cease to exist.
11 GC is single threaded or multi threaded?
Ans: Garbage Collection is multi threaded from JDK1.3 onwards.
12 what are the good programming practices for better memory management?
Ans: a. We shouldn’t declare unwanted variables and objects.
b. We should avoid declaring variables or instantiating objects inside loops.
c. When an object is not required, its reference should be nullified.
d. We should minimize the usage of String object and SOP’s.
13 When is the Exception object in the Exception block eligible for GC?
Ans: Immediately after Exception block is executed.
14 When are the local variables eligible for GC?
Ans: Immediately after method’s execution is completed.
15 If an object reference is set to null, Will GC immediately free the memory held by that object?
Ans: No. It will be garbage collected only in the next GC cycle.