Thursday, July 29, 2021

Top 10 Garbage Collection Interview Questions and Answers for Java Programmers

GC Interview Questions Answer in Java
Garbage collection interview questions are very popular in both core Java and advanced Java Interviews. Apart from  Java Collection and Thread many tricky Java questions stem Garbage collections which are tough to answer. In this Java Interview article, I will share some questions from GC which is asked in various core Java interviews. These questions are based upon the concept of How Garbage collection works, Different kinds of Garbage collectors, and JVM parameters used for garbage collection monitoring and tuning. As I said GC is an important part of any Java interview so make sure you have good command in GC. One more thing which is getting very important is the ability to comprehend and understand Garbage collection Output, more and more interviewer are checking whether the candidate can understand GC output or not.

During Java interview, they may provide a snippet of GC output and ask various questions based on that like Which Garbage collector is used, whether the output is from the major collection or minor collection, How much memory is free from GC, What is the size of new generation and old generation after GC, etc. 

I have included a few Garbage collection interview questions and answers from GC output to help with that. It’s recommended to prepare questions from Java collection,  multithreading, and programming along with Garbage collection to do well in Java interviews at any stage.



Interview questions on Java Garbage collection

Java Garbage collection Interview Question Answer for 4+ experienceHere are some Garbage collection Interview questions from my personal collection, which I have created from my experience and with the help of various friends and colleagues who have shared GC interview questions with me. 

Actually, there are a lot many questions than What I am sharing here but to keep this post small I thought to only share some questions, I can think of a second part of the GC interview question if you guys find this useful.



Question 1 - What is the structure of Java Heap? What is Perm Gen space in Heap?
Answer: In order to better perform in Garbage collection questions in any Java interview, It’s important to have a basic understanding of  Java Heap space. To learn more about the heap, see my post 10 points on Java heap space

By the way, Heap is divided into different generations e.g. new generation, old generation, and PermGen space.PermGen space is used to store class’s metadata and filling of PermGen space can cause java.lang.OutOfMemory: PermGen space. It's also worth noting to remember the JVM option to configure PermGen space in Java.



Question 2 - How do you identify minor and major garbage collections in Java?
Answer: Minor collection prints “GC” if garbage collection logging is enabled using –verbose:gc or -XX:PrintGCDetails, while Major collection prints “Full GC”. This Garbage collection interview question is based on an understanding of the Garbage collection output. As more and more Interviewer is asking a question to check the candidate’s ability to understand GC output, this topic becomes even more important.



Question 3 - What is the difference between ParNew and DefNew Young Generation Garbage collector?
Answer: This Garbage Collection interview question is recently asked by one of my friends. It requires more than average knowledge on GC to answer this question. 

By the way, ParNew and DefNew are two young generation garbage collector. ParNew is a multi-threaded GC used along with concurrent Mark Sweep while DefNew is a single-threaded GC used along with Serial Garbage Collector.

And, if you are serious about improving your advanced JVM skill and learn things like taking and analyzing heap dumps then highly recommend you to join these Java performance courses on Udemy. 



Question 4 - How do you find GC resulted due to calling System.gc()?
Answer: Another GC interview question is based on GC output. Similar to the major and minor collection, there will be the word “System” included in the Garbage collection output.



Question 5 - What is the difference between Serial and Throughput Garbage collectors?
Answer: Serial Garbage collector is a stop the world GC which stops application thread from running during both minor and major collection. Serial Garbage collector can be enabled using JVM option -XX:UseSerialGC and it's designed for Java application which doesn't have pause time requirement and has client configuration. 

The Serial Garbage collector also defaulted GC in JDK 1.4 before ergonomics was introduced in JDK 1.5. Serial GC is most suited for small applications with fewer threads while throughput GG is more suited for large applications. On the other hand Throughput garbage collector is a parallel collector where minor and major collection happens in parallel taking full advantage of all the system resources available like multiple processors. 

Though both major and minor collection runs on stop-the-world fashion and introduced pause in the application. Throughput Garbage collector can be enable using -XX:UseParallelGC or -XX:UseOldParallelGC

It increases the overall throughput of application my minimizing time spent in Garbage collection but still has long pauses during full GC. 

This is a kind of Garbage collection interview question that gives you an opportunity to show your knowledge in detail while answering. I always suggest answering these kinds of questions in detail.  See Java Performance The Definitive Guide for more details on this topic.

garbage collection interview question



Question 6 – When does an Object become eligible for Garbage collection in Java?
Answer: An object becomes eligible for garbage collection when there is no live reference for that object or it can not be reached by any live thread. The cyclic reference doesn’t count as a live reference and if two objects are pointing to each other and there is no live reference for any of them, then both are eligible for GC. Also Garbage collection thread is a daemon thread that will run by JVM based upon the GC algorithm and when runs it collects all objects which are eligible for GC.



Question 7 - What is finalize method in Java? When does Garbage collector calls finalize method in Java?
Answer: Finalize method in Java also called finalizer is a method defined in java.lang.Object and called by Garbage collector before collecting any object which is eligible for GC. Finalize() method provides the last chance to object to do cleanup and free any remaining resource, to learn more about finalizers, read What is finalize method in Java.



Question 8 - If Object A has reference to Object B and Object B refer to Object A, apart from that there is no live reference to either object A or B, Does they are eligible for Garbage collection?
This Garbage collection interview questions is related question 5 “When object become eligible for Garbage collection”. An object becomes eligible for Garbage collection if there is no live reference for it. It can not be accessible from any Thread and cyclic dependency doesn’t prevent Object from being Garbage collected. This means in this case both Object A and Object B are eligible of Garbage collection. See How Garbage collection works in Java for more details.



Question 9 -Can we force the Garbage collector to run at any time?
Answer: No, you can not force Garbage collection in Java. Though you can request it by calling Sytem.gc() or its cousin Runtime.getRuntime().gc(). It’s not guaranteed that GC will run immediately as a result of calling these methods.



Question 10 - Does Garbage collection occur in permanent generation space in JVM?
Answer : This  is a tricky Garbage collection interview question as many programmers are not sure whether PermGen space is part of Java heap space or not and since it maintains class Meta data and String pool, whether its eligible for garbage collection or not. 

By the way Garbage Collection does occur in PermGen space and if PermGen space is full or cross a threshold, it can trigger Full GC. If you look at the output of GC you will find that PermGen space is also garbage collected. This is why correct sizing of PermGen space is important to avoid frequent full GC. You can control size of PermGen space by JVM options -XX:PermGenSize and -XX:MaxPermGenSize.


garbage collection interview questions


Question 11 : How to you monitor garbage collection activities?
Answer: One of my favorite interview questions on Garbage collection, just to check whether the candidate has ever monitored GC activities or not. You can monitor garbage collection activities either offline or real-time. You can use tools like JConsole and VisualVM VM with its Visual GC plug-in to monitor real time garbage collection activities and memory status of JVM or you can redirect Garbage collection output to a log file for offline analysis by using -XlogGC=<PATH> JVM parameter. Anyway you should always enable GC options like -XX:PrintGCDetails -X:verboseGC and -XX:PrintGCTimeStamps as it doesn't impact application performance much but provide useful states for performance monitoring.


Question 12: Look at below Garbage collection output and answer following question :
[GC
       [ParNew: 1512K->64K(1512K), 0.0635032 secs]
       15604K->13569K(600345K), 0.0636056 secs]
       [Times: user=0.03 sys=0.00, real=0.06 secs]

 1. Is this output of Major Collection or Minor Collection ?
 2. Which young Generation Garbage collector is used ?
 3. What is size of Young Generation, Old Generation and total Heap Size?
 4. How much memory is freed from Garbage collection ?
 5. How much time is taken for Garbage collection ?
 6. What is current Occupancy of Young Generation ?

This Garbage collection Interview questions is completely based on GC output. Following are answers of above GC questions which will not only help you to answer these question but also help you to understand and interpret GC output.

Answer 1:  It's Minor collection because of "GC" word, In case of Major collection, you would see "Full GC".

Answer 2: This output is of multi-threaded Young Generation Garbage collector "ParNew", which is used along with CMS concurrent Garbage collector.

Answer 3: [1512K] which is written in bracket is total size of Young Generation, which include Eden and two survivor space. 1512K on left of arrow is occupancy of Yong Generation before GC and 64K is occupancy after GC. On the next line value if bracket is total heap size which is (600345K). If we subtract size of young generation to total heap size we can calculate size of Old Generation. This line also shows occupancy of heap before and after Garbage collection.

Answer 4: As answered in previous garbage collection interview question, second line shows heap occupancy before and after Garbage collection. If we subtract value of right side 13569K, to value on left side 15604K, we can get total memory freed by GC.

Answer 5: 0.0636056 secs on second line denotes total time it took to collect dead objects during Garbage collection. It also include time taken to GC young generation which is shown in first line (0635032 secs).

Answer 6: 64K 

Here is few more interesting Garbage collection Interview question for your practice, I haven’t provided answers of all garbage collection interview questions. If you know the answer than you can post via comments.

Question -  What is the difference between -XX:ParallelGC and -XX:ParallelOldGC?
Question - When do you ConcurrentMarkSweep Garbage collector and Throughput GC?
Question -  What is difference between ConcurrentMarkSweep and G1 garbage collector?
Question -  Have you done any garbage collection tuning? What was your approach?


These were some Garbage collection interview questions and answers, may help on your Java Interview preparation. If you have got any interesting interview questions related to GC then don’t forget to share them with us.

Other Java Interview resources from Javarevisited

10 comments :

James said...

Good questions. Much better than any other list of Garbage collection interview Questions in Java, My favorite among all is question related to GC logs. This is the most practical stuff I would like to See in Java programmer if claims he understand GC in Java.

Anonymous said...

How can I see what garbage collector is running on my java process ? I dont have access to the java paramters in my appserver. I have acces to the gc log.

Gautam said...

I was asked, How to reduce GC pause time in Java application? This was an interview to work in there high frequency system, where latency was very important. My answer was primarily based on my experience that Major collection introduce stop the world pause. So in order to reduce major collection, we can either create short lived object, which will get collected during minor collection without pause or better create Immortal object, which doesn't get GC'd.

What is your view on this question? Does my answer is good enough, is there any GC tuning setting related to this?

Anonymous said...

Why don't you put next set of questions on GC that you have in your bank. No matter how many, please put those in subsequent parts and give the links for those in this post [if possible].

Thanks a lot for putting such wonderful set of questions.

Unknown said...

I'm sorry to tell you this, but JAVA is still crap. You can still code viruses with it but since those retards who had to receive a higher education just to delve into this stuff can't easily code a virus the company thinks that it's okay to claim that it's safe. Even with it's sand-model, it's safe. Fact is, it's not boys. And it's a crappy language. Get used to it.

Anonymous said...

Garbage Collection in Java is a big topic and with every new release of JDK it becomes more and more sophisticated. Expect release of new Garbage collector algorithm in every major release e.g. G1 or Garbage First collection from JDK 1.7 release. In order to judge a candidate in Garbage Collection tuning or how much work he has really done in GC, I would ask these questions :

1) My Java application suddenly becomes slow for brief period, what could be the reason? or Some time our latency spikes without any external trigger, what could be causing it?

2) How do you choose between Serial and Parallel Garbage Collector? What is difference between Parallel and Concurrent Garbage Collector?

3) How does G1 Garbage Collector works in Java?

What do you think of these questions guys?

yyc said...

Hi I love your blog but I find the answer of question 3 is not correct.

DefNew is the printed name of young generation associated with Serial Garbage Collector using single threaded copying GC algorithms.

ParNew is also the printed name of young generation associated with ParNew Garbage Collector using multithreading copying GC algorithms instead of CMS GC algorithem, which is just a multithreading version of Serial Garbage Collector.

Anonymous said...

I was asked the below question in a gc interview.
Why do we need Survivor2... Wasn't the eden and survivor1 sufficient. Why did Java divide young generation into "3" sub-divisions and not just "2". Do you have an answer to that

Anonymous said...

DefNew stands for default New generation garbage collector which is single threaded and collects GC eligible object from young generation. ParNew stands for parallel new generation garbage collector, which collects object from young generation but uses multiple threads.

Gagandeep Singh said...

I was asked the below question in a gc interview.
Why do we need Survivor2... Wasn't the eden and survivor1 sufficient. Why did Java divide young generation into "3" sub-divisions and not just "2". Do you have an answer to that

I guess to avoid the fragmentation problems. We need to copy the data again and at the same time maintain the count so its better to copy that in another section. Like if we remove data from various indexes of an array its better to copy that data to new array rather than moving the data an index or two.

Post a Comment