Skip to Content
Course content

223: Thread-Safe Singleton Patterns in Kotlin

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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:

  1. Replace the MutableMap with a thread-safe alternative.
  2. Convert the version counter to an atomic type.
  3. Ensure that the updateSetting method 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]
    }
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.