Kotlin thread safe native lazy singleton with parameter

后端 未结 3 2026
感情败类
感情败类 2020-12-28 15:44

In java we can write thead-safe singletons using double Checked Locking & volatile:

    public class Singleton {         


        
3条回答
  •  执念已碎
    2020-12-28 16:15

    Object declaration is exactly for this purpose:

    object Singleton {
        //singleton members
    }
    

    It is lazy and thread-safe, it initializes upon first call, much as Java's static initializers.

    You can declare an object at top level or inside a class or another object.

    For more info about working with objects from Java, please refer to this answer.


    As to the parameter, if you want to achieve exactly the same semantics (first call to getInstance takes its argument to initialize the singleton, following calls just return the instance, dropping the arguments), I would suggest this construct:

    private object SingletonInit { //invisible outside the file
        lateinit var arg0: String
    }
    
    object Singleton {
        val arg0: String = SingletonInit.arg0
    }
    
    fun Singleton(arg0: String): Singleton { //mimic a constructor, if you want
        synchronized(SingletonInit) {
            SingletonInit.arg0 = arg0
            return Singleton
        }
    }
    

    The main flaw of this solution is that it requires the singleton to be defined in a separate file to hide the object SingletonInit, and you cannot reference Singleton directly until it's initialized.

    Also, see a similar question about providing arguments to a singleton.

提交回复
热议问题