RSS

How does the Garbage Collector work?

03 May

The garbage collector releases resources and memory for objects stored on the heap.

The garbage collector runs in its own thread and normally runs automatically, under well-defined circumstances. When the garbage collector runs, other threads in an application are halted because the garbage collector may move objects in memory and must update pointers to the correct addresses for these objects.

The garbage collector takes the following steps to reclaim resources:  

  1. It marks every object as dead; objects are considered dead unless proved otherwise.
  2. It starts from objects referenced on the stack, marking referenced objects as alive. It performs this recursively; if an object that is already marked as alive references another object, that object is also marked as alive. The garbage collector includes logic to prevent infinite recursion, for example, where there is a circular reference between two objects.
  3. It checks whether any of the objects that have been marked as dead have a destructor that must be run. Running the destructor is referred to as finalization. Any objects that require finalization are moved to a data structure maintained by the garbage collector called the freachable queue. The freachable queue stores pointers to objects that require finalization before their resources can be reclaimed.
  4. Objects added to the freachable queue are marked as alive because there is now a valid reference to them; the destructor must be run before their memory can be reclaimed. Objects are normally added to the freachable queue only once.
  5. Objects marked as alive are moved down the heap to form a contiguous block, defragmenting the heap. References to objects (on the stack and in other objects on the heap) moved by the garbage collector are updated.
  6. Other threads resume.
  7. On a separate thread, objects added to the freachable queue are finalized. After an object is finalized, the pointer to that object is removed from the freachable queue. Objects are not removed from memory until the next time the garbage collector runs.

You can download this video to understand this …

 

Tags: , , , , , , , , , ,

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

 
%d bloggers like this: