Memory model
- Kotlin course
- Expert
- Lesson 21/47
- 5 min
Learn the Kotlin/Native memory model.
The new memory model
Kotlin/Native initially used a strict thread isolation: each thread had its own heap and nothing was shared. The new memory model relaxed that.
In the new model there is relaxed cross-thread sharing and a global stop-the-world garbage collector. This aligns Kotlin/Native behaviour with the JVM. The new model is default in Kotlin 1.9+; old settings like binaryOption("memoryModel", "experimental") are gone. This makes mutableSharedState more natural to write; freezing is largely history.
A Counter example
In the new memory model, a Counter class can be shared across threads. The old model required freezing here; the new one does not.
Example: class Counter(private var n: Int = 0) { fun inc() { n += 1 }; fun get(): Int = n }. In the new model this class can be built in one coroutine and inc() called in another; no freeze() needed. The old model would throw InvalidMutabilityException here. In this lesson's exercise you will write a simple Counter and see the new model's relief.
Practice Write Counter
Define class Counter(private var n: Int = 0). Method fun inc() should increase n by one; fun get(): Int should return n. In main, build val c = Counter(), call c.inc() twice, and write println(c.get()).
Starter code
// add the Counter class
fun main() {
// call inc twice and print the get result
}Sample solution
class Counter(private var n: Int = 0) {
fun inc() { n += 1 }
fun get(): Int = n
}
fun main() {
val c = Counter()
c.inc(); c.inc()
println(c.get())
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match memory model
| Term | Meaning |
|---|---|
New model |
Shared heap |
Old model |
Thread isolation |
GC |
Garbage collector |
freeze |
Legacy freezing |
2 What did the new memory model remove?
- The freeze requirement Correct answer
- Coroutines
- Class definitions
- Type inference
Explanation: The new model made freezing unnecessary; sharing is now free.
3 Complete the inc method
class Counter(private var n: Int = 0) {
fun ____() { n += 1 }
fun get(): Int = n
}
class Counter(private var n: Int = 0) {
fun inc() { n += 1 }
fun get(): Int = n
}
Explanation: inc() increases the counter by one.