Wednesday, July 06, 2011

How does garbage collection work? [Java]

It seems to me that the importance of garbage collection in Java (and other garbage collected languages) is disproportional to the explanations given about it. While there would be millions of articles when you look for JavaFX examples, there would be only a couple if you tried to search about the “Parallel Compacting Collector†mentioned in Sun’s memory management whitepaper.

Since I wanted to understand better how the garbage collection is currently implemented in the Java VM and to see what’s ahead, I’ve scourged the internet a bit and found many interesting articles and slides. With the searches, it became like the old saying: there is a lot of stuff you don’t know, but there’s even more stuff you don’t even know you don’t know. This post is my summary of what I’ve found, but this is just the way I understand the explained material in publications and whitepapers; if I’m wrong somewhere, please do correct me.

The basics of garbage collection

The garbage collector first performs a task called marking. The garbage collector traverses the application graph, starting with the root objects; those are objects that are represented by all active stack frames and all the static variables loaded into the system. Each object the garbage collector meets is marked as being used, and will not be deleted in the sweeping stage.

The sweeping stage is where the deletion of objects take place. There are many ways to delete an object: The traditional C way was to mark the space as free, and let the allocator methods use complex data structures to search the memory for the required free space. This was later improved by providing a defragmenting system which compacted memory by moving objects closer to each other, removing any fragments of free space and therefore allowing allocation to be much faster:

Memory%20collection.png

Read more: Chaotic Java
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=http://chaoticjava.com/posts/how-does-garbage-collection-work/

Posted via email from Jasper-Net