Chapter 97. The Young, the Old, and the Garbage
María Arias de Reyna
One of the major advantages of Java is that developers have not had to worry (much) about memory. In contrast to many other languages around at the time of its launch, Java has, since the beginning, freed unused memory automatically. But that doesn’t mean Java developers don’t need to know the basics of how Java handles memory. There can still be memory leaks and bottlenecks.
Java divides its memory into two segments:
| Heap | Instances, variables…your data |
| Nonheap/perm | Code, metadata…for the JVM |
To care about memory in Java, we should focus on the heap. It is divided into two generations depending on their lifetime: young and old. The young generation (aka the nursery) contains short-lived objects. The old generation contains structures that have survived longer.
The young generation is divided in two:
| Eden | Where objects are created |
| Survivor | An in-between, limbo state through which an instance will pass when moving from the young to the old space |
The Garbage Collector
The garbage collector (GC) is the system cleaning the memory. There are different implementations, but in general it performs two tasks:
| Minor collection | Reviews the young generation |
| Major collection | Reviews all memory, young and old |
The GC runs at the same time as the normal app execution. Each execution of the GC involves a pause ...