Using @ Volatile lateinit var with Double-Checked Locking in Kotlin: Is It Safe?
Автор: vlogommentary
Загружено: 2026-01-08
Просмотров: 0
Explore whether using a @ Volatile lateinit var property initialized with double-checked locking in Kotlin provides the same thread safety and atomicity as a nullable property.
---
This video is based on the question https://stackoverflow.com/q/79421729/ asked by the user 'Bass' ( https://stackoverflow.com/u/1343979/ ) and on the answer https://stackoverflow.com/a/79421857/ provided by the user 'Sweeper' ( https://stackoverflow.com/u/5133585/ ) at 'Stack Overflow' website. Thanks to these great users and Stackexchange community for their contributions.
Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: Can a @ Volatile lateinit var be atomically initialized using a DCL pattern in Kotlin?
Also, Content (except music) licensed under CC BY-SA https://meta.stackexchange.com/help/l...
The original Question post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license, and the original Answer post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license.
If anything seems off to you, please feel free to drop me a comment under this video.
---
Understanding Thread-Safe Initialization in Kotlin with @ Volatile lateinit var
Initializing shared properties safely across threads is critical in concurrent programming. A commonly used pattern is double-checked locking (DCL), which minimizes synchronization overhead by checking initialization status both before and after acquiring a lock.
This post examines if applying DCL to a Kotlin @ Volatile lateinit var is semantically equivalent and equally safe as using a nullable @ Volatile property.
The Problem
We want to lazily initialize a singleton-style property ensuring:
Atomic initialization: The property must be fully initialized before any thread accesses it.
Visibility guarantees: Changes should be visible immediately to other threads.
Classic DCL in Kotlin using a nullable String? looks like this:
[[See Video to Reveal this Text or Code Snippet]]
Here, property!! asserts non-null after the initialization.
Using lateinit var Instead
The question arises: can we write an equivalent version with a lateinit var?
[[See Video to Reveal this Text or Code Snippet]]
::property.isInitialized checks if the lateinit property was initialized.
Accessing an uninitialized lateinit property throws UninitializedPropertyAccessException.
Are They Semantically Equivalent?
Both approaches compile down to essentially the same JVM bytecode. Behind the scenes, lateinit properties are just regular fields.
The isInitialized check is conceptually similar to a null check on a nullable property.
The critical difference lies in the exception thrown on uninitialized access:
property!! throws a NullPointerException if accessed before initialization.
lateinit access throws UninitializedPropertyAccessException.
This difference does NOT impact thread-safety or atomicity guarantees.
Important Considerations
Kotlin's concurrency model and JVM memory model enforcement are not formally specified by Kotlin itself.
The JVM's memory model and the use of the @ Volatile annotation ensure visibility and ordering guarantees similar to Java.
Using a lock combined with @ Volatile variable provides thread-safe lazy initialization akin to well-known patterns in Java.
Summary
It is safe and semantically equivalent to use @ Volatile lateinit var with a DCL pattern as with a nullable @ Volatile var.
The thread-safety comes primarily from JVM's volatile semantics and proper locking.
The difference is mainly in handling uninitialized state exceptions, which does not affect concurrency correctness.
When in doubt, or for cleaner code, consider Kotlin's lazy delegate for thread-safe lazy initialization:
[[See Video to Reveal this Text or Code Snippet]]
This uses synchronization internally and is simpler for most cases.
Using lateinit in combination with DCL works, but lazy is often a cleaner alternative.
Доступные форматы для скачивания:
Скачать видео mp4
-
Информация по загрузке: