Question

I've heard that Java has automatic garbage collection. How does it know when I'm finished with data, and to free some memory space?

Answer

A low priority thread takes care of garbage collection automatically for the user. During idle time, the thread may be called upon, and it can begin to free memory previously allocated to an object in Java. But don't worry - it won't delete your objects on you!

When there are no references to an object, it becomes fair game for the garbage collector. Rather than calling some routine (like free in C++), you simply assign all references to the object to null, or assign a new class to the reference.

Example :

pubic static void main(String args[])
{
	// Instantiate a large memory using class
	MyLargeMemoryUsingClass myClass = new MyLargeMemoryUsingClass(8192);

	// Do some work
	for ( .............. )
	{
		// Do some processing on myClass
	}

	// Clear reference to myClass
	myClass = null;

	// Continue processing, safe in the knowledge
	// that the garbage collector will reclaim myClass
}

If your code is about to request a large amount of memory, you may want to request the garbage collector begin reclaiming space, rather than allowing it to do so as a low-priority thread. To do this, add the following to your code

System.gc();

The garbage collector will attempt to reclaim free space, and your application can continue executing, with as much memory reclaimed as possible (memory fragmentation issues may apply on certain platforms).


Back