Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Kotlin's singletons thread safe?

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.

like image 455
alfongj Avatar asked May 12 '15 00:05

alfongj


People also ask

Are singletons thread-safe?

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.

Are singletons thread-safe C++?

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.

Are Kotlin objects thread-safe?

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.

How do I make singleton thread-safe?

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.


1 Answers

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

like image 110
Sergey Mashkov Avatar answered Oct 07 '22 21:10

Sergey Mashkov