Kotlin thread safe native lazy singleton with parameter

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

    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(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)
    }
    

    The singleton initialization will be lazy and thread-safe.

提交回复
热议问题