tags:

views:

4400

answers:

12
+10  Q: 

System.gc() in java

I know that garbage collection is automated in java. But I understood that if you write System.gc() in your code the java vm may or may not decide at runtime to do a garbage collection at that point. how does this work precisely? On what basis/parameters exactly does the VM decide to do (or not do) a GC when it sees a System.gc()? Are there maybe examples in which case it is a good idea to put this in your code?

+3  A: 

Too complex of a concept to full detail here, but this article should help you:

http://chaoticjava.com/posts/how-does-garbage-collection-work/

Geoffrey Chetwood
+6  A: 

In practice, it usually decides to do a garbage collection. The answer varies depending on lots of factors, like which JVM you're running on, which mode it's in, and which garbage collection algorithm it's using.

I wouldn't depend on it in your code. If the JVM is about to throw an OutOfMemoryError, calling System.gc() won't stop it, because the garbage collector will attempt to free as much as it can before it goes to that extreme. The only time I've seen it used in practice is in IDEs where it's attached to a button that a user can click, but even there it's not terribly useful.

jodonnell
you can force a garbage collection in jconsole
bene
@bene Can you really "force" it? Is jconsole just calling System.gc()?
John Meagher
+3  A: 

System.gc() is implemented by the VM, and what it does is implementation specific. The implementer could simply return and do nothing, for instance.

As for when to issue a manual collect, the only time when you may want to do this is when you abandon a large collection containing loads of smaller collections--a Map<String, LinkedList<...>> for instance--and you want to try and take the perf hit then and there, but for the most part, you shouldn't worry about it. The GC knows better than you (sadly) most of the time.

Patrick
+6  A: 

You have no control over GC in java -- the VM decides. I've never run across a case where System.gc() is needed. Since a System.gc() call simply SUGGESTS that the VM do a garbage collection and it also does a FULL garbage collection (old and new generations in a multi-generational heap), then it can actually cause MORE cpu cycles to be consumed than necessary.

In some cases, it may make sense to suggest to the VM that it do a full collection NOW as you may know the application will be sitting idle for the next few minutes before heavy lifting occurs. For example, right after the initialization of a lot of temporary object during application startup (i.e., I just cached a TON of info, and I know I won't be getting much activity for a minute or so). Think of an IDE such as eclipse starting up -- it does a lot to initialize, so perhaps immediately after initialization it makes sense to do a full gc at that point.

Dustin
A: 

in short-

parameters is VM dependent.

example usage- can't think of one for runtime/production apps, but it is useful to run it for some profiling harnesses, like calling

// test run #1
test();
for (int i=0; i<10; i++) { 
// calling repeatedly to increase chances of a clean-up
  System.gc(); 
}
// test run #2
test();
mataal
+1  A: 

I can't think of a specific example when it is good to run explicit GC.

In general, running explicit GC can actually cause more harm than good, because an explicit gc will trigger a full collection, which takes significantly longer as it goes through every object. If this explicit gc ends up being called repeatedly it could easily lead to a slow application as a lot of time is spent running full GCs.

Alternatively if going over the heap with a heap analyzer and you suspect a library component to be calling explicit GC's you can turn it off adding: gc=-XX:+DisableExplicitGC to the JVM parameters.

zxcv
+1  A: 

You need to be very careful if you call System.gc(). Calling it can add unnecessary performance issues to your application, and it is not guaranteed to actually perform a collection. It is actually possible to disable explicit System.gc() via the java argument "-XX:+DisableExplicitGC".

I'd highly recommend reading through the documents available at Java HotSpot Garbage Collection for more in depth details about garbage collection

David Schlosnagle
+3  A: 

The only example I can think of where it makes sense to call System.gc() is when profiling an application to search for possible memory leaks. I believe the profilers call this method just before taking a memory snapshot.

Guillermo Vasconcelos
Yes, that's what I do as well. The values returned by Runtime.freeMemory() e.g. are only really meaningful after a System.gc(), because normally you want to know how much memory is blocked by uncollectable instances. Only to be used in debugging/memory profiling of course, never in production.
sleske
+1  A: 

Most JVMs will kick of a GC (depending on the -XX:DiableExpliciteGC and -XX:+ExplicitGCInvokesConcurrent switch). But the specification is just less well defined in order to allow better implementations later on.

The spec needs clarification: http://bugs.sun.com/view_bug.do?bug_id=6668279

Internally the gc method is used by RMI and NIO, and they require synchronous execution, which: this is currently in discussion:

http://bugs.sun.com/view_bug.do?bug_id=5025281

eckes
A: 

Normally, the VM would do a garbage collection automatically before throwing an OutOfMemoryException, so adding an explicit call shouldn't help except in that it perhaps moves the performance hit to an earlier moment in time.

However, I think I encountered a case where it might be relevant. I'm not sure though, as I have yet to test whether it has any effect:

When you memory-map a file, I believe the map() call throws an IOException when a large enough block of memory is not available. A garbage collection just before the map() file might help prevent that, I think. What do you think?

A: 

If you use Direct memory buffers, the JVM doesn't run the GC for you even if you are running low on directory memory. If you call ByteBuffer.allocateDirect() and you get an OOM error you can find this call is fine after triggering a GC manually.

Peter Lawrey
A: 

we can never force garbage collection. System.gc is only suggesting vm for garbage collection, however, really what time the mechanism runs, nobody knows, this is as stated by JSR specifications.

lwpro2