Senior
Tell me about garbage collectors in Java, what types are there, and if you have experience configuring JVM.
sobes.tech AI
Answer from AI
In Java, there are several types of garbage collectors, each optimized for different scenarios:
- Serial GC — a single-threaded collector, simple and efficient for single-processor systems or small applications.
- Parallel GC (Throughput Collector) — multi-threaded, focused on maximum throughput, suitable for server applications.
- CMS (Concurrent Mark Sweep) — an older implementation with minimal pauses, runs concurrently with the application but can lead to fragmentation.
- G1 (Garbage First) — a modern collector that divides the heap into regions, aims to minimize pauses, well-suited for large heaps.
- ZGC and Shenandoah — low-latency collectors that work almost without pauses, suitable for very large applications requiring minimal delays.
Configuring the JVM typically involves choosing the appropriate collector based on load and latency requirements, tuning memory parameters (heap size, young/old generation), and monitoring and analyzing collections using tools (jstat, VisualVM, JMC). For example, for an application with high responsiveness requirements, G1 can be selected and maximum pause time can be set via -XX:MaxGCPauseMillis.
Example of running with G1 GC and pause time limit:
java -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -Xms2g -Xmx2g -jar app.jar