Reputation: 1429
How exactly JVM determines that it should Garbage Collector?Is there any way to restrict JVM not to invoke GC?
Upvotes: 7
Views: 757
Reputation: 718758
How exactly JVM determines that it should Garbage Collector?
It depends.
If you are using the throughput collector, then the JVM runs the GC when it cannot allocate a new object in the space (or one of the spaces) where it needs to be allocated.
If you are using a low pause collector, then the JVM triggers the GC when the free space ratio drops bellow a configurable level.
Is there any way to restrict JVM not to invoke GC?
No. If the JVM decides it needs to run the GC, it will run it. The only thing you can do is tell the JVM to ignore application code calls to System.gc()
.
Upvotes: 5
Reputation: 533492
Generally speaking the GC only runs when it needs to. An exception, the concurrent mark sweep will start prematurely to avoid having to stop the application.
IMHO, The simplest/best solution is to not create so much garbage. You can use a memory profiler to reduce the amount of garbage you are producing. This will reduce the size of your collections and how often they occur. In extreme cases you can avoid collecting during the day or even for a whole week.
A benefit of reducing garbage is you reduce flushing your CPU caches with garbage. Your L3 cache is only a few MB and you create a few MB of garbage you will have effectively pushed out useful information, slowing down your application.
Upvotes: 0
Reputation: 42020
It really depends on the implementation of the virtual machine.
In another hand:
Explicit requests for garbage collection are a bellwether indicating likely performance problems.
Code Correctness: Call to System.gc()
Calls to
System.gc()
,Runtime.getRuntime().gc()
, andSystem.runFinalization()
are not advised. Code should have the same behavior whether the garbage collection is disabled using the option-Xdisableexplicitgc
or not. Moreover, "modern" jvms do a very good job handling garbage collections. If memory usage issues unrelated to memory leaks develop within an application, it should be dealt with JVM options rather than within the code itself.
PMD Rule DoNotCallGarbageCollectionExplicitly
Upvotes: 1
Reputation: 500257
Typically, the JVM decides to run a garbage collection cycle when one of the heap areas gets close to being full. Note that, ultimately, the decision is up to the JVM.
As to instructing the JVM to not perform GC for a while, there is no reliable and portable way to do this (other than avoiding heap allocations altogether).
If you are trying to minimize GC pauses, the Java Performance book has some good material.
Upvotes: 3
Reputation: 14149
You cannot tell the JVM not to invoke GC, but you can tell the JVM to ignore calls to System.gc()
via -XX:+DisableExplicitGC
.
Upvotes: 4