1

I am testing some JDKs and need to trigger garbage collection multiple times. How can I easily do this in a simple program? Examples would be extremely helpful. Thank you.

rupes0610
  • 221
  • 1
  • 5
  • 18

3 Answers3

3

See here for a good discussion on garbage collection. You can request that it is run (as noted by previous answers), but it is not a guarantee, so you should not assume too much with the call. Your best option is to create and destroy new objects many, many times. To allow them to be destroyed, create them in a block and close it again. Perhaps something like this:

for(int i = 0; i < MAX; ++i) {
    {
        Integer i = new Integer(0);
    }
}

And you could monitor the memory use externally?

Carl
  • 895
  • 5
  • 9
  • +1 for the only solution that *guarantees* to eventually cause GC. However consider creating `byte[1024]` or bigger to avoid excessive CPU usage. Also `new Integer()` is never a good idea, but `Integer.valueOf(0)` will always return the same object... – Tomasz Nurkiewicz Jul 26 '12 at 20:15
  • A JITter that does escape analysis could allocate these objects on the stack and get rid of them immediately, meaning GC may still never get triggered. – cHao Jul 26 '12 at 20:15
  • Those are good points, thanks. Off my head, just thinking of an object to use as an example. – Carl Jul 26 '12 at 20:17
  • Maybe then it's a good idea to pass the object to a very low cost method somewhere? I'm not very familiar with how the escape analysis would be done. Perhaps something that changes one of the bytes and returns is enough to skip that? – Carl Jul 26 '12 at 20:24
  • Escape analysis checks whether the object is assigned or used anywhere in a way that'd mandate a longer lifetime. In this case, it might be enough to assign the reference to a member variable; i'd think that'd be enough to defeat escape analysis, since now the object has to be able to survive past the lifetime of the current stack frame. – cHao Jul 26 '12 at 20:28
2

You can use System.gc() to request for Garbage Collection

This SO discussion might be interesting in the context of your question

Community
  • 1
  • 1
Sujay
  • 6,664
  • 2
  • 27
  • 49
1

From Oracle docs use System.gc()

public static void gc()

Runs the garbage collector. 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.

The call System.gc() is effectively equivalent to the call:

Runtime.getRuntime().gc()

bragboy
  • 32,353
  • 29
  • 101
  • 167