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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
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.
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
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.
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.
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