7.1 How to choose the right garbage collector

If your application doesn't have strict latency requirements, you should just run the application and let the JVM itself choose the right collector.

In most cases, the default settings work fine. If necessary, you can adjust the heap size to improve performance. If performance is still not as expected, try modifying the collector to suit your application's requirements.

  • Sequential . If the application has a small data set (up to about 100 MB) and/or it will run on a single processor without any latency requirements.
  • Parallel . If the priority is application peak performance and there are no latency requirements (or pauses of one second or more are acceptable).
  • CMS/G1 . If response time is more important than overall throughput, and garbage collection pauses should be shorter than one second.
  • ZGC . If response time is high priority and/or a very large heap is involved.

7.2* Recommendations for garbage collection

Avoid manual triggers

In addition to the basic mechanisms of garbage collection, one of the most important points about this process in Java is that it is non-deterministic. That is, it is impossible to predict when exactly at run time it will occur.

Using the System.gc() or Runtime.gc() methods, you can include a hint in your code to start the garbage collector, but this does not guarantee that it will actually run.

Use analysis tools

If you don't have enough memory to run your application, you'll experience slowdowns, long garbage collection times, "world stop" events, and eventually out-of-memory errors. This may indicate that the heap is too small, but it may also indicate that the application has a memory leak.

You can use a monitoring tool like jstat or Java Flight Recorder to see if the heap usage grows indefinitely, which could indicate a bug in the code.

Prefer the default settings

If you have a small, standalone Java application, you probably won't need to set up garbage collection. The default settings will serve you well.

Use JVM flags to customize

The best approach to setting up garbage collection in Java is to set JVM flags. Flags can be used to set the garbage collector (for example, Serial, G1, and so on), the initial and maximum size of the heap, the size of the heap partitions (for example, Young generation, Old generation), and much more.

Choose the right faucet

A good guideline in terms of initial settings is the nature of the custom application. For example, the concurrent garbage collector is efficient, but often raises “world stop” events, making it more suitable for internal processing where long pauses are acceptable.

At the same time, the CMS garbage collector is designed to minimize latency, which makes it ideal for web applications where responsiveness is important.