I have two functions below one is insert() and other one is startGC().
I will call insert() method first which will take some 300MB of heap space. After that I will call startGC() which should release the memory allocated in heap because all the vector objects are local to the function but its not happening.
private void insert()
{
Vector v=new Vector();
Vector v1=new Vector();
Vector v2=new Vector();
String str="Hello";
for (long i = 0L; i < 999999L; i++) {
v.add(str + i);
v1.add(str + i);
v2.add(str + i);
}
v=null;
v1=null;
v2=null;
}
private void startGC()
{
System.gc();
}
My Question:
1) Why Garbage collect is not working in this example.
2) How to make JVM to garbage collect all unused memory blocks.
Any code sample to achieve the same.
From the JavaDoc:
Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.
As already said, you can only suggest the GC to delete your objects. The only thing you might do is setting the heapmax (for example: -Xmx512m). You can affect the run of the gc this way. This is probably one of the biggest disadvantages of Java. If you really need the heap, your have to use languages like cpp, which won´t use a vm to compile the application.
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