Skip to content

Instantly share code, notes, and snippets.

@ZahraHeydari
Last active May 28, 2024 11:16
Show Gist options
  • Save ZahraHeydari/1dd4f97b0a9f3b46af52697894046671 to your computer and use it in GitHub Desktop.
Save ZahraHeydari/1dd4f97b0a9f3b46af52697894046671 to your computer and use it in GitHub Desktop.
How Singleton pattern is implemented in Kotlin.

Singleton pattern in Kotlin

Regular object class in Kotlin provides the Singleton behavior (not allowed to have any constructor inside the object class!). It's thread-safe and instantiated lazily, when we access it for the first time.

Thread-safe and lazy:

object Singleton {
    // code to be executed
}

How to make a class Singleton in Kotlin?

Double-Check Locking. Thread safe and lazy:

class Singleton private constructor() {

    companion object {

        @Volatile private var instance: Singleton? = null //Volatile modifier is necessary

        fun getInstance() =
            instance ?: synchronized(this) {
                instance ?: Singleton().also { instance = it }
            }
    }
}

Simple, thread safe and lazy:

class Singleton private constructor() {

    companion object {
    
        val INSTANCE: Singleton by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { Singleton() }
    }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment