In java we can write thead-safe singletons using double Checked Locking & volatile:
public class Singleton {
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.