Selecting a garbage collector for application in Java


In this tutorial, we’ll discuss why there could be need to define the garbage collector for your application. What are the factors which help in decision making for selecting the garbage collector.

Java can be run on different types of machines and devices. Java HotSpot VM provides multiple garbage collectors to meet different requirements. Java SE selects the most appropriate garbage collector based on the machine it is run. However, this selection may not be good enough and developers and administrators may require more control on the type of garbage collection to be used. This could be the case when developers and administrators have strict performance guidelines and goals.

Guidelines for selecting garbage collector?

Serial collector is usually suitable for small application with up to approximately 100 megabytes of heap size. However, when the heap size is more, serial garbage collector is not suitable. Serial collector is single thread collector and therefore has less overhead in comparison to other collectors.

The selection of garbage collector depends on multiple factors like data set, heap size, type of the system running application and processor.

Following are the base guidelines for selection of garbage collector:

  • If the application has small data set (approximately up to 100 MB) and will be run on a single processor and has no pause-time requirements, then use serial garbage collector. Serial Garbage collector can be enabled using option -XX:+UseSerialGC.
  • If application performance is first priority and there are no pause-time requirements or pauses of one or more seconds are acceptable, then either let VM select the garbage selector or use parallel garbage collector. Parallel collector can be enabled using option -XX:+UseParallelGC.
  • If response time is more important than overall throughput and the need is to keep keep garbage collection pauses shorter, then select the Garbage-First (G1) garbage collector. G1 garbage collector can be enabled by using option -XX:+UseG1GC.
  • If response time of application is highest priority, then select The Z Garbage Collector. The Z Garbage Collector can be enabled using option -XX:UseZGC.