In java we can write thead-safe singletons using double Checked Locking & volatile:
public class Singleton {
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 object
s from Java, please refer to this answer.
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.