Explain the garbage collection mechanism in Java?
GC works automatically and isn't worth looking into for most novice developers. Remember that Java is a robust language with years of support and testing. The chances of you implementing GC better than the "out of the box" solutions is small.
This doesn't mean you shouldn't explore it and understand how it works.
Garbage collection periodically "frees up" unused memory in your application. Garbage collection is an automatic process so you never have to explicitly call GC.While you can "request" GC to run via JVM programming interfaces, this is not recommended.There are a lot of things to know about garbage collection. For beginner to more intermediate developers, the recommendation is to let the garbage collector do its thing.
For more advance developers, it's sometimes worth it to look at the different options available to the JVM in regards to which GC you use as well as how much memory you allocate to heap, Eden space, etc.
garbage collection cleans up all the mess :)
The garbage collection mechanism works like this:
When the JVM starts, the underlying OS allocates a specified amount of memory to the JVM heap space.
The heap space is where objects are created, class and method information are stored, etc.
When you create an object, the stack usually manages a reference to this object and the actual object is stored in memory.
While the stack follows a relatively simple FIFO algorithm for cleaning up memory after method/thread execution, the heap is much larger and more permanent. For these reasons, the heap requires a more sophisticated approach to cleaning up memory.
Enter Garbage Collection. GC divides the heap space into areas based on object lifespan (young vs old generation). GC leverages several algorithms to efficiently "mark" and free up unused memory blocks.
There are different implementations of the GC. Not only do different JVM's implement it differently, different collectors can be specified as part of JVM argument list.
While some GC work concurrently with the application execution, others work in separate threads. Stop the world (STW) events are common with GC. The application must pause while garbage is collected.