Java Garbage Collectors
Brief introduction to GC
The Garbage Collector keeps track of every object in the heap-space and removes the unused ones.
Basically, GC works in two simple steps, Mark and Sweep.
Properties
Implementions
There are multiple GCs that suit different application requirements. For example, the Serial GC, Parallel GC, and the G1GC that is currently the default GC algorithm.
Serial GC - This is the simplest GC implemention, Suited for small applications using a single thread for garbage collection and freezing other application threads during execution, but not for multithreaded applications such as servers. Enable it by using the following argument:
java -XX:+UseSerialGC -jar Application.java
Parallel GC - Runs in multiple threads to manage heap space, optimizing throughput (some times is also called throughput collectors) but also freezes other application threads while performing GC. To enable it, we can use the following argument:
java -XX:+UseParallelGC -jar Application.java
G1GC - Shares the processor resources with the application, and is designed for applications that require lower pause times. G1 stands for "Garbage first". It partitions the heap in a set of heap regions in contiguos ranges of memory running it's marking phase to determine the liveness of objects knowing which regions are mostly empty, yielding a considerable amount of free space. To enable it if you are not using >JDK7, you can use the following argument:
java -XX:+UseG1GC -jar Application.java
There is also the ZGC, that aims to offer low-latency by performing all expensive work concurrently without stopping the application for more than 10ms. That is possible by creating "colored pointers" to perform concurrent operations while threads are running. It was firsttly added on Java 11 as an experimental option, but is production-ready since Java 15 and may acquire the status of default GC on the next versions.
Conclusion