Memory and garbage collection
suggest changeWhen executing on the Java Virtual Machine (JVM), Kotlin code relies on the JVM's automatic memory management and garbage collection (GC). Understanding how Kotlin constructs map to JVM memory—and how Kotlin features like inlining, value classes, and structured concurrency affect allocation—is critical for building high-throughput, low-latency applications.
The JVM Memory Structure
The JVM divides memory into several distinct areas:
+-------------------------------------------------------------------+
| JVM Process |
| |
| +-----------------------------+ +---------------------------+ |
| | Heap Memory | | Non-Heap Memory | |
| | +-----------------------+ | | +---------------------+ | |
| | | Young Gen (Eden/Survivor)| | | Metaspace (Classes) | | |
| | +-----------------------+ | | +---------------------+ | |
| | | Old / Tenured Gen | | | +---------------------+ | |
| | +-----------------------+ | | | Code Cache (JIT) | | |
| +-----------------------------+ +---------------------------+ |
| |
| +-------------------------------------------------------------+ |
| | Thread Stacks (Stack Frames, Local Variables, Primitives) | |
| +-------------------------------------------------------------+ |
+-------------------------------------------------------------------+
- Stack Memory: Each thread has its own stack. Method execution frames, primitive local variables, and object references reside here. Memory is allocated and deallocated instantly as functions are pushed and popped.
- Heap Memory: Shared by all threads. All class instances, arrays, and boxed primitives are allocated on the heap and managed by the garbage collector.
- Metaspace: Stores class metadata and bytecode definitions (static fields live on the heap since Java 8).
Garbage Collectors in the JVM
Modern JVMs provide several GC algorithms tuned for different workloads:
- G1GC (Garbage-First): The default collector since Java 9. Divides the heap into regions and prioritizes collecting regions with the most garbage to meet target pause times.
- ZGC / Shenandoah: Ultra-low-latency concurrent collectors with sub-millisecond pause times, even on terabyte-scale heaps.
- Parallel GC: High-throughput collector that stops application threads during collections; ideal for batch processing.
Kotlin Features That Optimize Memory
Kotlin provides language features designed to eliminate heap allocations:
1. inline Functions
In standard higher-order functions, passing a lambda creates a Function object instance on the heap and, if it captures variables, a closure object. Marking the function with inline instructs the compiler to copy the function body and lambda directly into the call site:
// Inlined: Zero object allocations at runtime
inline fun <T> measureTime(block: () -> T): T {
val start = System.nanoTime()
try {
return block()
} finally {
val elapsed = (System.nanoTime() - start) / 1_000_000
println("Executed in ${elapsed}ms")
}
}
fun main() {
// The lambda body is copied inline; no Function1 instance is allocated
val sum = measureTime {
(1..1_000_000).sum()
}
}
2. Value Classes (@JvmInline value class)
Value classes wrap an underlying primitive or reference without creating a heap object:
@JvmInline
value class Seconds(val value: Int)
fun delayOperation(duration: Seconds) {
println("Waiting for ${duration.value} seconds")
}
fun main() {
// No 'Seconds' object is allocated on the heap; compiles to primitive int
delayOperation(Seconds(30))
}
3. Avoiding Primitive Boxing
Kotlin represents all numbers as objects syntactically, but compiles them to JVM primitives whenever possible. Be aware of hidden boxing:
fun main() {
val unboxed: Int = 42 // Compiles to primitive 'int' (Stack)
val boxed: Int? = 42 // Boxed into java.lang.Integer (Heap)
val list: List<Int> = listOf(1, 2, 3) // Boxed Integers on Heap
val array: IntArray = intArrayOf(1, 2, 3) // Primitive int[] on Heap (Zero boxing!)
}
Tip: Use specialized primitive arrays (
IntArray,LongArray,DoubleArray) instead ofArray<Int>orList<Int>when processing large numerical buffers.
Weak and Soft References
When building in-memory caches, holding strong references prevents the GC from reclaiming objects, leading to OutOfMemoryError. Use WeakReference or SoftReference:
import java.lang.ref.WeakReference
import java.lang.ref.SoftReference
class Bitmap(val name: String, val buffer: ByteArray)
class ImageCache {
// SoftReference is cleared by GC only when memory is low
private val cache = mutableMapOf<String, SoftReference<Bitmap>>()
fun put(key: String, bitmap: Bitmap) {
cache[key] = SoftReference(bitmap)
}
fun get(key: String): Bitmap? {
val ref = cache[key]
val bitmap = ref?.get()
if (bitmap == null) {
cache.remove(key) // Evicted by GC
}
return bitmap
}
}
Preventing Memory Leaks in Coroutines
Coroutines that are launched without structured lifecycle management can leak references and retain large objects:
Anti-pattern: GlobalScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
// BAD: Retains HeavyService indefinitely if job runs long
class HeavyService {
val largeBuffer = ByteArray(10_000_000)
fun startListening() {
GlobalScope.launch {
while (true) {
// Kept alive forever
}
}
}
}
Idiomatic: Structured Concurrency (CoroutineScope)
Tie the coroutine lifecycle to the component lifecycle and cancel on teardown:
import kotlinx.coroutines.*
class SafeService : CoroutineScope {
private val job = SupervisorJob()
override val coroutineContext = Dispatchers.Default + job
fun start() {
launch {
// Task executes within managed scope
}
}
fun close() {
// Cancels all child jobs and releases memory
job.cancel()
}
}
Best Practices
- Use
inlinefor functions accepting lambdas: Eliminates anonymous function allocations and closure captures. - Prefer
IntArrayoverList<Int>for high-throughput math: Avoids boxing overhead and decreases GC frequency. - Adopt structured concurrency: Avoid
GlobalScopeso coroutines cancel cleanly with their parent scope. - Profile with JDK Flight Recorder (JFR) & VisualVM: Profile memory allocation rates and identify retaining paths before optimizing blindly.