Sunday, September 27, 2009

Garbage Collection


Garbage collection (GC) is a form of automatic memory management. The garbage collector attempts to reclaim memory used by objects that will never be accessed or mutated again by the application.

Garbage collection essentially is a 2-step process:
  •  It determines which objects in a program will not be accessed in the future,
  •  And then reclaims the resources used by these objects.

Automatic memory management can eliminate common problems, such as forgetting to free an object and causing a memory leak, or attempting to access memory for an object that has already been freed. It aids programmers in their efforts to make programs more stable, because it prevents several runtime errors. E.g. it prevents dangling pointer errors, where a reference to a de-allocated object is used.

  1.  In Java, the JVM takes care of releasing unused memory by keeping track of the references to allocated resources. Whenever the JVM detects that a resource is no longer referenced by a valid reference, the resource is garbage-collected.
  1.  In C#, garbage collection is handled by the CLR with similar functionality to that of the JVM. The CLR garbage collector periodically checks the memory heap for any unreferenced objects, and releases the resources held by these objects.

No comments: