50

I know that Java have its own garbage collection, but sometimes I want to delete the garbage manually. Is there any way to do the work like that? And considering that I have a long or very long function which declares many variables, is this a good idea to delete the unused memory immediately after using instead of auto collection at the end of the function? If I delete garbage manually, does it affect the speed of my application? Thanks for helping!

1
  • 1
    It is a good idea to set your variables to null after use. HotSpot will do that for you, too, but not with a 100% guarantee. Commented Jul 4, 2012 at 16:46

8 Answers 8

57

There is no direct and immediate way to free memory in java. You might try to persuade the garbage collector to take away some object using the well known:

Object obj = new Object();
// use obj
obj = null;
System.gc();

but there is no guarantee that this will actually free memory immediately.

While this applies to heap memory, stack allocated items can only be freed when the function returns.

Sign up to request clarification or add additional context in comments.

2 Comments

There is a guarantee that the GC will do its best to do something immediately. Javadoc: "When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects." There is just no guarantee exactly what will be cleaned up.
very useful for recursive functions
19

Why do you want to delete the garbage "manually"? If it's because you're out of memory, recall that Java is going to run garbage collection before actually throwing OutOfMemoryError. And if you are really out of memory, then there is no garbage for even you to manually remove.

Declaring a variable does not allocate memory on the heap. Making an object with new does. JVMs can do escape analysis to even GC object references that have not gone out of scope but are not used anymore before the end of the method.

If you mean you proactively want to free up memory at a certain point where system resources are not critical, then use better JVM tuning like using the parallel GC algorithms.

"Manually" garbage collecting by setting things to null likely slows things down if only because you pay the cost of nulling references pointlessly, or, invoking GC more times than is needed.

Comments

4

You can call System.gc(); which might lead the garbage collector to cleanup. But sure this will affect the performance of your application. In general it doesn't make sense to try to "optimize" anything here.

Comments

4

It's not worth doing this manually, since the garbage collector will usually do a better job, and doing it yourself isn't likely going to make a noticeable difference in your application.

If you must, you can set the variable references to null, and call System.gc(), and this will invoke the garbage collector manually.

Comments

3

A very common suggestion is to use System.gc() Which the JVM may choose to ignore. You can also use the scoping, for example:

import java.io.*;
public class AutoVariableTest
{
    public static void main(String[] args) throws Exception
    {
        String fileName = "test.txt";
        {// This is local block just to keep auto variable in check
            File file = new File(fileName); // file is not visible outside the scope and is available for garbage collection
            BufferedReader br = null;

            try{
                br = new BufferedReader(new FileReader(file));
                // ...
            }finally{
                if(br != null)
                    br.close();
            }
        }// local block end
    }
}

Comments

3

If you intend to reduce the amount of memory used after a certain point, you might be better off using arrays for your variables so that you can set an array to null once it is no longer necessary. This way, it takes much less time for the garbage collector to clean up all of your data.

Comments

3

You can assign null to variables, verify that there are no references to these objects, and call System.gc(). It is only a suggestion for JVM to call a GC, but there is no guarantee. Garbage collection call slows your application up to a freeze (stop-the-world GC).

Comments

1

Java is not suitable if you are trying to manage memory ! Or you write your own Garbage Collection mechanism in JVM if you have lots of time

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.