Posted by: lrrp | February 3, 2015

Interview questions on Java Garbage collection

 How do you identify minor and major garbage collection in Java?

Answer: Minor collection prints “GC” if garbage collection logging is enable using –verbose:gc or -XX:PrintGCDetails, while Major collection prints “Full GC”. This Garbage collection interview question is based on understanding of Garbage collection output. As more and more Interviewer are asking question to check candidate’s ability to understand GC output, this topic become even more important.

Question 3 – What is difference between ParNew and DefNew Young Generation Garbage collector?

Answer : This Garbage Collection interview questions is recently asked to one of my friend. It require more than average knowledge on GC to answer this question. By the way ParNew and DefNew is two young generation garbage collector. ParNew is a multi-threaded GC used along with concurrent Mark Sweep while DefNew is single threaded GC used along with Serial Garbage Collector.

Question 4 – How do you find GC resulted due to calling System.gc()?

Answer : Another GC interview question which is based on GC output. Similar to major and minor collection, there will be a word “System” included in Garbage collection output.

Question 5 – What is difference between Serial and Throughput Garbage collector?

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 have client configuration. Serial Garbage collector was also default GC in JDK 1.4 before ergonomics was introduced in JDK 1.5. Serial GC is most suited for small application with less number of thread while throughput GG is more suited for large applications. On the other hand Throughput garbage collector is parallel collector where minor and major collection happens in parallel taking full advantage of all the system resources available like multiple processor. Though both major and minor collection runs on stop-the-world fashion and introduced pause in application. Throughput Garbage collector can be enable using -XX:UseParallelGC or -XX:UseOldParallelGC. It increases 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 questions which gives you an opportunity to show your knowledge in detail while answering. I always suggest to answer these kind of questions in detail.

Question 6 – When does an Object becomes 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. Cyclic reference doesn’t count as live reference and if two objects are pointing to each other and there is no live reference for any of them, than both are eligible for GC. Also Garbage collection thread is a daemon thread which will run by JVM based upon 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 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 to 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. Which 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 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 result of calling these method.

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 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.

Question 11 – What are the different types of references in java?
Java has a more expressive system of reference than most other garbage-collected programming languages, which allows for special behavior for garbage collection. A normal reference in Java is known as a strong reference. The java.lang.ref package defines three other types of references–soft, weak, and phantom references. Each type of reference is designed for a specific use.

A SoftReference can be used to implement a cache. An object that is not reachable by a strong reference (that is, not strongly reachable), but is referenced by a soft reference is called softly reachable. A softly reachable object may be garbage collected at the discretion of the garbage collector. This generally means that softly reachable objects will only be garbage collected when free memory is low, but again, it is at the discretion of the garbage collector. Semantically, a soft reference means “keep this object unless the memory is needed.”

A WeakReference is used to implement weak maps. An object that is not strongly or softly reachable, but is referenced by a weak reference is called weakly reachable. A weakly reachable object will be garbage collected during the next collection cycle. This behavior is used in the class java.util.WeakHashMap. A weak map allows the programmer to put key/value pairs in the map and not worry about the objects taking up memory when the key is no longer reachable anywhere else. Another possible application of weak references is the string intern pool. Semantically, a weak reference means “get rid of this object when nothing else references it.”

A PhantomReference is used to reference objects that have been marked for garbage collection and have been finalized, but have not yet been reclaimed. An object that is not strongly, softly or weakly reachable, but is referenced by a phantom reference is called phantom reachable. This allows for more flexible cleanup than is possible with the finalization mechanism alone. Semantically, a phantom reference means “this object is no longer needed and has been finalized in preparation for being collected.”

Question 12 : How to you monitor garbage collection activities?

Answer : One of my favorite interview questions on Garbage collection, just to check whether 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 13: 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

What is memory leak?
A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesn’t get garbage collected.

How to find the size of an object?
The heap size of an object can be found using –
Runtime.totalMemory()-
Runtime.freeMemory() .

Consider a scenario in which the admin want to sure that if someone has written System.exit() at some part of application then before system shutdown all the resources should be released. How is it possible?
This is possible using Runtime.getRuntime().addShutdownHook(Thread hook).

Straight from Java Spec:
This method registers a new virtual-machine shutdown hook.

The Java virtual machine shuts down in response to two kinds of events:

  1. The program exits normally, when the last non-daemon thread exits or when the exit (equivalently,   System.exit) method is invoked, (or)
    2. The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently.

When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method.

Once the shutdown sequence has begun it can be stopped only by invoking the halt method, which forcibly terminates the virtual machine.

How does Java allocate stack and heap memory?
Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class). In Java methods local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed.

In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space. The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronisation through your code.

Here are 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 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?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: