Switch to full style
Java2 codes,problems ,discussions and solutions are here
Post a reply

What Is Garbage Collection?

Wed Jul 04, 2007 12:12 am

What Is Garbage Collection?
--------------------------------------


A key feature of Java is its garbage-collected heap, which takes care of freeing dynamically allocated memory that is no longer referenced. Because the heap is garbage-collected, Java programmers don't have to explicitly free allocated memory.

The name "garbage collection" implies that objects that are no longer needed by the program are "garbage" and can be thrown away. A more accurate and up-to-date metaphor might be "memory recycling." When the program no longer references an object, the heap space it occupies must be recycled so that the space is available for subsequent new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such un-referenced objects. In the process of freeing un-referenced objects, the garbage collector must run any finalizers of objects being freed.

The Java programmer must keep in mind that it is not generally possible to predict exactly when un-referenced objects will be garbage collected so it is not possible to predict when object finalizers will be run. Java programmers, therefore, should avoid writing code for which program correctness depends upon the timely finalization of objects.
Although you can't tell Java to explicitly reclaim the memory of a specific de-referenced object, there is a way to tell the JVM to perform garbage collection, which may result in the desired memory being reclaimed. Invoking the garbage collector requires a simple two-step process. First you create a Java Runtime object. Then, after creating the Runtime object, you'll invoke the gc() method ("garbage collector") of the Runtime class.

java code
Runtime r = Runtime.getRuntime(); 
r.gc();


Why garbage collection?

First, Garbage collection relieves programmers from the burden of freeing allocated memory. Knowing when to explicitly free allocated memory can be very tricky.

A second advantage of garbage collection is that it helps ensure program integrity. Garbage collection is an important part of Java's security strategy. Java programmers are unable to accidentally (or purposely) crash the JVM by incorrectly freeing memory.



Post a reply
  Related Posts  to : What Is Garbage Collection?
 garbage collection work in java     -  
 Interface Collection and Class Collection     -  
 Can an object be garbage collected and it is still reachable     -  
 Eligible objects for garbage collectors     -  
 java Collection Syntax     -  
 java(collection framework)     -  
 Huge collection of SEMINAR Topics     -  

Topic Tags

Java Basics