Are Kotlin's singletons thread safe?

2019-04-18 03:08发布

问题:

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.

回答1:

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