GC tuning
- Java course
- Expert
- Lesson 33/46
- 5 min
Learn G1 and ZGC garbage collector settings.
Garbage collectors
Java has several main garbage collectors (GC). G1 is the default since Java 9; it offers balanced throughput and latency. ZGC and Shenandoah do concurrent relocation for low latency; they target sub-millisecond pauses even on large heaps.
The GC is chosen with -XX:+UseG1GC, -XX:+UseZGC or -XX:+UseShenandoahGC. The choice depends on whether the workload prioritises throughput or latency.
Heap and GC tuning
Heap size is set with -Xmx (max) and -Xms (initial). A small heap triggers frequent GC; a very large heap can cause long pauses. A target pause time is given with a flag such as -XX:MaxGCPauseMillis=200.
For latency-sensitive applications ZGC or Shenandoah is preferred; for throughput-oriented batch work G1 is chosen. Before tuning, the real load must be measured with JFR.
Practice Write the GcConfig class
Define class GcConfig with a static String config(String gc, int heapMb) method that returns "-XX:+Use" + gc + " -Xmx" + heapMb + "m". In main print System.out.println(config("G1GC", 2048));.
Starter code
// Define the GcConfig class: config method builds the flag string
// main: print the config for G1GC and 2048MBSample solution
class GcConfig {
static String config(String gc, int heapMb) {
return "-XX:+Use" + gc + " -Xmx" + heapMb + "m";
}
public static void main(String[] args) {
System.out.println(config("G1GC", 2048));
}
}Expected output
-XX:+UseG1GC -Xmx2048m
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the garbage collectors
| Term | Meaning |
|---|---|
G1 |
Default collector |
ZGC |
Low latency |
Shenandoah |
Concurrent relocation |
-Xmx |
Max heap |
2 Complete the GC flag
-XX:+Use____ -Xmx2g
-XX:+UseG1GC -Xmx2g
Explanation: -XX:+UseG1GC selects the G1 collector.
3 Which GC is preferred for low latency?
- Serial GC
- ZGC Correct answer
- Parallel GC
- G1 GC
Explanation: ZGC targets very short pauses with concurrent relocation.