HenSh
02/07/2024, 3:00 PMprivate val shared: CustomSingleton by _lazy_(LazyThreadSafetyMode.SYNCHRONIZED) *{* CustomSingleton() *}*
I aim to access this singleton and his custom variable, which includes an array (read and write) from different threads.
Or can you please share what I need to learn 🙂
I really appreciate any help you can provide.Jan Holešovský
02/07/2024, 3:17 PMHenSh
02/07/2024, 3:23 PMclass Singleton {
private val array = ArrayDeque<String>()
companion object {
val shared: Singleton by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { Singleton() }
}
fun getElement(index: Int): String {
return array[index]
}
fun add(item: String) {
array.add(item)
}
fun size(): Int {
return array.size
}
}
The question is how to support multithreading. Is it safe to access the array from different threads?Pablichjenkov
02/07/2024, 3:51 PMJan Holešovský
02/08/2024, 10:23 AMobject Singleton { ... }
, without the companion object { val shared ... }
thing? That should be thread safe according to https://stackoverflow.com/questions/30179793/are-kotlins-singletons-thread-safeHenSh
02/08/2024, 10:32 AMobject Singleton { ... }
without companion object
So the last and most important case I need to understand if after the initialization of the singleton instance, the read and write from the array inside this instance are thread safe?Jan Holešovský
02/08/2024, 12:36 PMHenSh
02/08/2024, 12:38 PM