Below is a sample code to check garbage collection. The process memory shown in Windows Task manager never comes down after executing the program. Please let me know if I am handling the Garbage Collection correctly. My question is why even after GC is completed successfully, why the memory usage shown in Task Manager never comes down. Why there is an accumulation of memory usage - I fear this may lead to OutOfMemoryError in my real application after executing big database operations.
Or that I should not bother about the process memory consumed as shown in the Task Manager & should concentrate only on JVM's free memory?
Please view the below programs & let me know for any issues.... Thanks much!
Below class just creates integers and adds it into a list
<edit> posting the output of program </edit>
Before - Total memory for JVM in Kilo Bytes-> 15872
Before - Free Memory -> 15590
Before - Used Memory in Kilo Bytes -> 281
Thread sleeping --- Please see the memory utilization in Task Manager
<---- Populating List Started --->
<---- Populating List Finished --->
Finalization called on TestGCInput Object..... hence the object is Garbage Collected Successfully!!!
After - Total memory for JVM in Kilo Bytes-> 229764
After - Free Memory -> 229628
After - Used Memory in Kilo Bytes -> 135
Ulf Dittmer wrote:Memory allocated to the JVM (which is what TaskManager reports) is never freed.
1. Can this scenario lead to OutOfMemoryError?
2. Is there a way to clear this memory leak?
3. If the memory reported by Task Manager reaches > 1200 or 1300 K, I can see Out of Memory error. Will that be because of this leak?
<edit> added ques</edit>
No. You will get OOMEs if your code uses more memory than the JVM is maximally allocated.
Is there a way to clear this memory leak?
It's not a leak. You can control precisely how much memory the JVM gets allocated via the -Xms and -Xmx options.
You need to differentiate between memory allocated to the JVM via the OS (which is what TaskManager is concerned with, and which never comes down), and memory allocated by the JVM internally for Java objects (which will come down as objects become eligible for GC).