Suggesting Kindly That the Garbage Collector Run

     

This you can do. The garbage collector runs in a separate thread from the thread of execution, reclaiming space here and there when it finds objects that can no longer be referenced, or other unreachable code.

The garbage collector has been around the block. She's seen objects come and go, every day throughout the years . And she's not about to take any lip from some upstart crow telling her how to manage her memory.

To suggest that the garbage collector run, which does not guarantee that it runs, try tempting her with this:

 

 System.gc(); 

Note that, like other methods in the System class, this is the effective equivalent of calling

 

 Runtime.getRuntime().gc(); 

This means that the Java Virtual Machine will have made its "best effort to reclaim space" (API documentation). But if the VM is busy, its best effort may not leave anyone thinking, "Whoa, that was really a good effort." In 99 cases out of 100, however, the call to gc() can be helpful, assuming that you need the memory back immediately, because the garbage collector will pick up method local variables very soon after the method returns.

Here is an example that demonstrates .

private void testGC(){

 

 System.out.println("Free mem kb before bad code: " + Runtime.getRuntime().freeMemory() / 1024); for (int i = 0; i < 100000; i++){ String s = new String("Object " + i); } System.out.println("Free mem kb AFTER bad code: " + Runtime.getRuntime().freeMemory() / 1024); System.gc(); System.out.println("Free mem kb after GC call: " + Runtime.getRuntime().freeMemory() / 1024); } 

And the result:

 

 Free mem kb before bad code: 1864 Free mem kb AFTER bad code: 1493 Free mem kb after GC call: 1898 

Notice that the garbage collector sees that all of these String objects are, as my friend John from Texas used to say, "a big show about nothing," and knows it can remove them. The call to the garbage collector freed up half a megabyte of memory. Running this program with the call to System.gc() commented out yields this result:

 

 Free mem kb before bad code: 1864 Free mem kb AFTER bad code: 1493 Free mem kb after GC call: 1493 



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net