When does System.gc() do anything

2018-12-31 07:01发布

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?

17条回答
余生无你
2楼-- · 2018-12-31 07:31

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.

查看更多
忆尘夕之涩
3楼-- · 2018-12-31 07:31

If you want to know if your System.gc() is called, you can with the new Java 7 update 4 get notification when the JVM performs Garbage Collection.

I am not 100% sure that the GarbageCollectorMXBean class was introduces in Java 7 update 4 though, because I couldn't find it in the release notes, but I found the information in the javaperformancetuning.com site

查看更多
泛滥B
4楼-- · 2018-12-31 07:32

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.

查看更多
无与为乐者.
5楼-- · 2018-12-31 07:34

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.

查看更多
琉璃瓶的回忆
6楼-- · 2018-12-31 07:35

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

The spec needs clarification: Bug #6668279: (spec) System.gc() should indicate that we don't recommend use and don't guarantee behaviour

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

Bug #5025281: Allow System.gc() to trigger concurrent (not stop-the-world) full collections

查看更多
登录 后发表回答