Kulwinder Singh
07/20/2022, 6:20 AMclass MyObject private constructor() {
companion object {
@Volatile
private var INSTANCE: MyObject? = null
fun isReadyInstance(): Boolean {
return (INSTANCE != null)
}
fun getInstance(): MyObject {
return INSTANCE ?: throw Exception("Error Instance is not initialized.")
}
fun createInstance() {
synchronized(this) {
if (INSTANCE == null) {
INSTANCE = MyObject()
}
}
}
fun deleteInstance() {
synchronized(this) {
INSTANCE = null
}
}
}
there is condition in my code to check for instance
if (MyObject.isReadyInstance()) {
MyObject.getInstance() //BUT HERE I GET -> "Error Instance is not initialized."
}
I think when isReadyInstance
returned true meanwhile at some other place deleteInstance
is called and therefore getInstance
returned null, but how can i make sure that it won’t happen ?Kunal Pasricha
07/20/2022, 6:27 AMfun getInstance(): MiniGameManager {
synchronized(this) {
if (INSTANCE == null) {
INSTANCE = MyObject()
}
}
return INSTANCE
}
couldn't we make getInstance like this?Kulwinder Singh
07/20/2022, 6:28 AMandylamax
07/20/2022, 7:52 AMKulwinder Singh
07/20/2022, 9:58 AMNick Allen
07/21/2022, 4:54 AMisReadyInstance
and getInstance
methods are inherently unsafe. They would have to be combined like in your createInstance. Though, the simplest equivalent would just be:
fun getInstanceOrNull(): MyObject? = INSTANCE
DALDEI
07/29/2022, 12:43 AM