I have written simple code in java as follows
public static void main(String[] args) {
String st ="Java";
StringBuffer sb = new StringBuffer(st);
long startTime = System.currentTimeMillis();
Runtime r = Runtime.getRuntime();
long startm = r.freeMemory();
System.out.println("Before running program free memory is: "+startm);
for(int i=0; i<10000; i++)
st+="is";
long endm = r.freeMemory();
System.out.println("After program free memory is: "+endm);
}
However the problem is when I run the program, free memory is increasing after loop is finished but it should be less than in beginning of the program. My output is as follows:
Before running program free memory is: 61089768
After program free memory is: 123747064
Please tell me why is that?
Your code is producing a lot of object garbage. The line
st+="is";
translates to:
st = new StringBuffer().append(st).append("is").toString();
This means each loop produces at least two objects of garbage.
Before entering the loop, there is already garbage on the object heap from the Java startup. Your loop triggers the garbage collector, freeing not only the unneeded objects from your program, but also all other objects left behind by the Java startup.
Start your program with the parameters -XX:+PrintGCDetails and you will see when the GC operates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With