Java garbage collection|Java garbage collection tutorial|Java garbage collection algorithm|Java garbage collection techniques|Java garbage collection

Java garbage collection|Java garbage collection tutorial|Java garbage collection algorithm|Java garbage collection techniques|Java garbage collection example|Java garbage collection tuning|Java garbage collection basics|Java garbage collection finalize

Garbage Collection

An automatic garbage collector deallocates memory for objects that are no longer needed by your program, thereby relieving you from the tedious and error-prone task of deallocating your own memory. As a consequence of automatic garbage collection and lack of pointers, a Java
object is either null or valid--there is no way to refer to an invalid or stale object
(one that has been deallocated).

To illustrate the effect of a garbage collector, consider the following C++ function that allocates 1000 objects on the heap via the new operator (a similar C function would allocate memory using calloc/malloc):

// C++ code
void f() {
T *t;
for (int i = 1; i <= 1000; i++) {
t = new T; // ack!!!!!
}
}

Every time the loop body is executed, a new instance of class T is instantiated, and t is pointed to it. But what happens to the instance that t used to point to? It's still allocated, but nothing points to it and therefore it's inaccessible. Memory in this state is referred to as "leaked" memory.

In the Java language, memory leaks are not an issue. The following Java method causes no ill effects:
// Java code
void f() {
T t;
for (int i = 1; i <= 1000; i++) {
t = new T();
}
}

In Java, each time t is assigned a new reference, the old reference is now available for garbage collection. Note that it isn't immediately freed; it remains allocated until the garbage collector thread is next executed and notices that it can be freed. Put simply, automatic garbage collection reduces programming effort, programming errors, and program complexity.

  © Free Blogger Templates Modic Template by For more Information : click Here

Back to TOP