Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Nov 18, 1998

Putting out the Trash Using the gc() Call

The gc() call on the Java Virtual Machine's garbage collector is often misunderstood. One of the reasons Java is such an easy language to program in is that it takes the burden of memory management away from the developer. Specifically, you never have to worry about deallocating memory that is held by resources in your running program. That's where the garbage collector comes in: you set your object to null and the garbage collector collects it. Simple. Or is it?

When exactly does the garbage collector collect unused memory? It doesn't collect it when you set the object to null; it collects memory periodically or when the system is running low on resources. So do you have any control over when the memory is freed? Java does provide a method gc() that may be used as follows:

 
  1. public void freeMemory () {
  2. String myString = new String("Free Me");
  3. // Do stuff with myString
  4. myString = null;
  5. Runtime rt = Runtime.getRuntime();
  6. rt.gc();
  7. }
On line 2, the String "Free Me" is created and this memory is assigned to the object myString. On Line 6, the object is set to null, so that it will be collected when the garbage collector runs. On Line 7, an instance of the current runtime is obtained and on 8, the call to gc() is made.

Please note that the call on Line 8 does not cause the garbage to be collected. It is merely a hint to the VM to free the memory as soon as it can. Also, when the garbage collector runs, it may not free the memory for the object that you just released.

So is there any use for setting the object to null and calling gc()? Yes, because you are helping the garbage collector free up unused memory and you are also telling it to do this ASAP. If the object myString ate up a lot of memory (instead of what is occupied by "Free Me"), you would definitely want to invoke gc() before you allocate more memory.

However, overusing the gc()call can be detrimental because you will be asking the garbage collector to run before it is normally scheduled to run. When the garbage collector runs, it consumes resources from the same pool used by your applications. Using this runtime call requires careful thought and programmers need to be aware that the memory is not freed immediately. You cannot force the garbage collector to pick up the trash at specific times. You can only politely ask it to do so when it can.

Ajit Sagar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap