Are Kotlin singletons (more specifically, object declarations) thread-safe by construction? If not, what is the best practice to write thread safe singletons in Kotlin?
I would guess they are, but I haven't been able to find any explicit statement about it in the docs.
Is singleton thread safe? A singleton class itself is not thread safe. Multiple threads can access the singleton same time and create multiple objects, violating the singleton concept. The singleton may also return a reference to a partially initialized object.
The beauty of the Meyers Singleton in C++11 is that it's automatically thread-safe. That is guaranteed by the standard: Static variables with block scope. The Meyers Singleton is a static variable with block scope, so we are done.
Fortunately, Kotlin provides a lot of syntactic sugar which will help us to make immutable objects, and more generally thread-safe code, without losing too much performance.
Thread Safe Singleton in JavaCreate the private constructor to avoid any new object creation with new operator. Declare a private static instance of the same class. Provide a public static method that will return the singleton class instance variable.
Kotlin "object" is thread-safe by construction. As you can see in any decompile/dumping tool, declared object is just final class with static instance initialization + language syntax sugar to simplify instance access
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With