Kotlin thread safe native lazy singleton with parameter

后端 未结 3 2010
感情败类
感情败类 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:02

    Kotlin has an equivalent of your Java code, but more safe. Your double lock check is not recommended even for Java. In Java you should use an inner class on the static which is also explained in Initialization-on-demand holder idiom.

    But that's Java. In Kotlin, simply use an object (and optionally a lazy delegate):

    object Singletons {
        val something: OfMyType by lazy() { ... }
    
        val somethingLazyButLessSo: OtherType = OtherType()
        val moreLazies: FancyType by lazy() { ... }
    }
    

    You can then access any member variable:

    // Singletons is lazy instantiated now, then something is lazy instantiated after.  
    val thing = Singletons.something // This is Doubly Lazy!
    
    // this one is already loaded due to previous line
    val eager = Singletons.somethingLazyButLessSo
    
    // and Singletons.moreLazies isn't loaded yet until first access...
    

    Kotlin intentionally avoids the confusion people have with singletons in Java. And avoids the "wrong versions" of this pattern -- of which there are many. It instead provides the simpler and the safest form of singletons.

    Given the use of lazy(), if you have other members each would individually be lazy. And since they are initialized in the lambda passed to lazy() you can do things that you were asking about for about customizing the constructor, and for each member property.

    As a result you have lazy loading of Singletons object (on first access of instance), and then lazier loading of something (on first access of member), and complete flexibility in object construction.

    See also:

    • lazy() function
    • Lazy thread safe mode options
    • Object declarations

    As a side note, look at object registry type libraries for Kotlin that are similar to dependency injection, giving you singletons with injection options:

    • Injekt - I'm the author
    • Kodein - Very similar and good
    0 讨论(0)
  • 2020-12-28 16:02

    I recently wrote an article on that topic. TL;DR Here's the solution I came up to:

    1) Create a SingletonHolder class. You only have to write it once:

    open class SingletonHolder<out T, in A>(creator: (A) -> T) {
        private var creator: ((A) -> T)? = creator
        @Volatile private var instance: T? = null
    
        fun getInstance(arg: A): T {
            val i = instance
            if (i != null) {
                return i
            }
    
            return synchronized(this) {
                val i2 = instance
                if (i2 != null) {
                    i2
                } else {
                    val created = creator!!(arg)
                    instance = created
                    creator = null
                    created
                }
            }
        }
    }
    

    2) Use it like this in your singletons:

    class MySingleton private constructor(arg: ArgumentType) {
        init {
            // Init using argument
        }
    
        companion object : SingletonHolder<MySingleton, ArgumentType>(::MySingleton)
    }
    

    The singleton initialization will be lazy and thread-safe.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题