0

I want to know if there is a way to stop and start the JVM performing Garbage Collection during runtime.

If there is not, why not? Surely this feature would make Java more suitable for safety critical applications?

  • 2
    Possible duplicate of [How can I disable Java garbage collector?](http://stackoverflow.com/questions/2927396/how-can-i-disable-java-garbage-collector) – OldProgrammer Aug 27 '16 at 21:13
  • 7
    If you could turn it off, it would make your program crash with `OutOfMemoryError`, even though there is memory to reclaim. That's even worse than GC delay for a "safety critical application". This is an example of the XY problem: You think the solution for a safety critical application is to stop GC. The answer is really about selecting the [*right* GC](https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/collectors.html) solution, not *preventing* GC. – Andreas Aug 27 '16 at 21:15
  • Is there a way to switch it on and off at **runtime**? During certain critical sections we wouldn't want GC to cause a Stop-the-World pause and crash a plane or something? – skeidsberget2365 Aug 27 '16 at 21:18
  • 2
    @skeidsberget2365 Have you thought about realtime VMs such as [JamaicaVM](https://www.aicas.com/cms/en/JamaicaVM)? – beatngu13 Aug 27 '16 at 21:26
  • @skeidsberget2365 This is a separate question, and possibly a good one. How can Java be used in time-critical applications when there are inevitable stops? (I don't know the answer though.) – Felix Dombek Aug 27 '16 at 21:29

2 Answers2

1

Actually, there is a way to stop Java GC. Just use the Epsilon GC algorithm that was introduced as an experimental feature in Java 11. Just add the following two arguments to your JVM's startup script:

-XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC

All or Nothing

Now just keep in mind that this Java GC algorithm does no GC at all. So if you do any object allocation in your code, eventually you'll hit an OutOfMemoryError and your app will crash. But if your JVM is short lived, and you don't think that's an issue, give Epsilon GC a try.

Just remember it's all or nothing. You can't force Java GC and you can't stop Java GC from happening if you use any of the other garbage collectors. The collector is non-deterministic, so control by programmers or admins just isn't possible out of the box.

Cameron McKenzie
  • 3,684
  • 32
  • 28
0

By default the JVM runs the JVM only needed. This means you can't turn off the GC or your program will fail.

The simplest way to avoid stopping the JVM is;

  • use a very small eden size so when it stops it will be less than some acceptable time.
  • or make the eden size very large and delay the GC until it hardly matters. e.g. you can reduce you garbage rate and run for 24 hours or longer between minor GCs.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130