Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Java System.gc() not working as expected?

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.

like image 634
Vasant Avatar asked Apr 19 '26 14:04

Vasant


2 Answers

  1. In what way isn't it working?
  2. You can't tell the JVM to start a Garbage Collection, you can only suggest that you think it is a good idea by invoking System.gc().

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.

like image 132
Keppil Avatar answered Apr 21 '26 02:04

Keppil


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.

like image 41
Christian Lendel Avatar answered Apr 21 '26 04:04

Christian Lendel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!