Tags

, , , ,

I believe to be a senior Java developer you must understand how GC works. Here I will give you some basic ideas about JVM Garbage Collection or GC.

1) Unlike C++, Java does not have de-constructor. the garbage collector finds the unnecessary (garbage) objects and removes them. A good idea to release a specific memory is set the object to null. Some people like to call the System.gc() method to remove the memory explicitly. System.gc() method will affect the system performance drastically, please do not do that.

2) Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.  If there is no memory space for creating new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space. Or it will throw an out-of-memory exception if too much time is being spent doing garbage collection. For example, if the JVM is spending more than 98% of the total time doing garbage collection and is recovering less than 2% of the heap, it will throw an out-of-memory exception.

3) HotSpot VM is separated into two parts one is called young generation the other one is called old generation. If you have an object foo (which is an instance of some class), the more garbage collection events it survives (if there are still references to it), the further it gets promoted. It starts in the young generation (which itself is divided into multiple spaces – Eden and Survivor) and would eventually end up in the tenured generation if it survived long enough.

The old generation basically performs a GC when the data is full. The execution procedure varies by the GC type, so it would be easier to understand if you know different types of GC.
According to JDK 7, there are 5 GC types. Please check the oracle web site to see details of those 5 types. I do not want to do much copy/paste
1. Serial GC
2. Parallel GC
3. Parallel Old GC (Parallel Compacting GC)
4. Concurrent Mark & Sweep GC  (or “CMS”)
5. Garbage First (G1) GC

4) GC tuning is a very complicated work.It largely depends on application profile, what kind of object application has and what are there average lifetime etc. for example if an application has too many short lived object then making Eden space wide enough or larger will reduces number of minor collections. You can also control size of both young and Tenured generation using JVM parameters for example setting -XX:NewRatio=3 means that the ratio among the young and tenured generation is 1:3 . Please be careful on sizing these generation.

5) JVM command line options –Xmx and -Xms is used to setup starting and max size for Java Heap. Ideal ratio of this parameter is either 1:1 or 1:1.

Advertisements