Synchronized singleton in Kotlin

Viewed 6438

I am new to Kotlin. Still learning basic syntax. I've heard about companion objects similar to static in Java. But don't know how to create synchronized singleton in Kotlin.

4 Answers

There are also other ways, but those two are the most simple ones to generate a singleton class

Method 1- Kotlin Way

object SingletonObj {
    init {
        // do your initialization stuff
    }
}

Method 2- Double Null Check Way in Kotlin

class SingletonObj {
    private constructor(context: Context)

    companion object {
        @Volatile private var mInstance: SingletonObj? = null

        public  fun get(context: Context): SingletonObj =
            mInstance ?: synchronized(this) {
                val newInstance = mInstance ?: SingletonObj(context).also { mInstance = it }
                newInstance
            }
    }
}

I think, little bit more research, and i found it . Here is how to do it . Please correct me if it can be done in better way.

companion object {
@Volatile private var INSTANCE: Singleton ? = null
 fun  getInstance(): Singleton {
         if(INSTANCE == null){
             synchronized(this) {
                 INSTANCE = Singleton()
             }
         }
         return INSTANCE!!
   }
}

Thread-safe and lazy:

class Singleton private constructor() {
    companion object {
        val instance: Singleton by lazy { Singleton() }
    }
}

Double null check already implemented inside by lazy.

Related