Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
223: Thread-Safe Singleton Patterns in Kotlin
Look, I've seen this in pull requests more times than I can count: a developer uses the object keyword in Kotlin and assumes that because the instance is a singleton, every operation inside it is magically thread-safe. It's a dangerous assumption that leads to some of the hardest-to-debug race conditions in production.
Thinking the 'object' keyword guarantees thread-safe state
Here is the misconception: "Kotlin's object is a singleton, and the JVM guarantees it's initialized thread-safely, so my data inside it is safe too."
That first part is true. The JVM ensures that the object instance is created only once, even if multiple threads try to access it for the first time simultaneously. But the state you put inside that object is a completely different story. If you have a mutable variable inside an object, you've essentially created a global variable. And global mutable state is a recipe for disaster.
// This is a trap. Do not do this in production.
object RequestCounter {
var count = 0
fun increment() {
count++ // This is NOT thread-safe
}
}
You might think count++ is a single operation, but it's actually three: read the value, increment it, and write it back. If two threads hit increment() at the exact same time, they might both read "10", both increment it to "11", and both write "11" back. You just lost a request count. I've spent entire weekends hunting down bugs exactly like this.
Using Atomic types and Concurrent collections for actual safety
To make a singleton truly thread-safe, you have to protect the data, not just the instance. For simple counters or flags, I always reach for java.util.concurrent.atomic. These use low-level CPU instructions (Compare-And-Swap) to ensure the operation is atomic without the heavy overhead of a full lock.
import java.util.concurrent.atomic.AtomicInteger
object RequestCounter {
private val count = AtomicInteger(0)
fun increment() {
count.incrementAndGet() // Now this is actually thread-safe
}
fun getCount(): Int = count.get()
}
If you're managing a map of data—say, a cache of user sessions—don't use a standard MutableMap wrapped in a singleton. Use ConcurrentHashMap. It allows multiple threads to read and write to different parts of the map simultaneously without locking the entire object.
Handling parameters with the Double-Checked Locking pattern
Now, there's a catch. The object keyword is great, but it doesn't allow you to pass parameters to the constructor. What if your singleton needs a Context or a Config object that isn't available until the app starts? You can't use object for that.
You'll be tempted to just use a nullable var and a synchronized block, but doing that on every access kills performance. This is where the "Double-Checked Locking" pattern comes in. It ensures you only synchronize the first time the instance is created.
class DatabaseManager private constructor(context: String) {
init {
println("Initializing DB with $context")
}
companion object {
@Volatile
private var INSTANCE: DatabaseManager? = null
fun getInstance(context: String): DatabaseManager {
// First check (no locking)
return INSTANCE ?: synchronized(this) {
// Second check (with locking) to prevent race condition
INSTANCE ?: DatabaseManager(context).also { INSTANCE = it }
}
}
}
}
Note the @Volatile annotation. This is non-negotiable. It tells the JVM that changes to INSTANCE must be immediately visible to all other threads. Without it, one thread might initialize the manager, but another thread might still see INSTANCE as null because it's reading a cached value from its own CPU core.
📋 Practical Task
Fixing the Race Condition in the GlobalSettingsManager
You have been handed a legacy GlobalSettingsManager singleton that is causing intermittent crashes and incorrect setting updates in a multi-threaded environment. The current implementation uses a standard HashMap and a simple var for a version tracker, which is causing ConcurrentModificationException and lost updates.
Your Task: Refactor the following code to be fully thread-safe. You must:
- Replace the
MutableMapwith a thread-safe alternative. - Convert the
versioncounter to an atomic type. - Ensure that the
updateSettingmethod is atomic so that the version is incremented every time a setting is changed.
// BROKEN CODE - FIX THIS
object GlobalSettingsManager {
private val settings = mutableMapOf<String, String>()
var version = 0
fun updateSetting(key: String, value: String) {
settings[key] = value
version++
}
fun getSetting(key: String): String? {
return settings[key]
}
}
There are no comments for now.