General musings on programming languages, and Java.

Monday, October 11, 2004

Lame Java Benchmarks - Freeing Memory

Someone said that Java doesn't free up memory to the OS during a program's execution, so this is a simple test of that assertion.

import java.util.ArrayList;
import java.util.List;

public final class Main
{
        public static void main(final String[] args) throws InterruptedException
        {
                allocate();
                System.out.println(Runtime.getRuntime().freeMemory());
                System.gc();
                System.out.println(Runtime.getRuntime().freeMemory());
                System.out.println("Here");

                Thread.sleep(60000);
        }

        private static void allocate() throws InterruptedException
        {
                List list=new ArrayList();

                for (int a=0;a<5000000;a++)
                        list.add(new Object());
        }
}           
The output of running ps aux repeatedly on Linux while this is running shows that the garbage collection never has an external effect. The output of the program is simply : 6207736 66317488 Here This demonstrates that the garbage collection is happening.

1 comment:

Anonymous said...

JVM has garbage collected some unnecessary objects and removed them from the heao after calling gc() but the allocated heap is not freed up and is not shrank. You can see this by looking at, say, the Mem Usage column of the Processes tab of the Windows Task Manager...

Blog Archive

About Me

A salsa dancing, DJing programmer from Manchester, England.