Understanding Kotlin Lazy Initialization: Usage, Source Code Analysis, and Best Practices
This article explains Kotlin's lazy initialization feature, describes its common usage patterns, dives into the internal source‑code implementations (Synchronized, Publication, and None), discusses thread‑safety concepts such as volatile and CAS, and provides practical recommendations for Android developers.
Kotlin's lazy (delayed initialization) allows developers to defer object creation until first use, offering performance benefits and thread‑safety by default when using the appropriate mode.
Common usage patterns are illustrated with simple examples, showing five ways to declare a lazy property and highlighting the most frequently used forms (especially modes 4 and 5).
Source‑code analysis focuses on the three concrete implementations of the Lazy interface:
SynchronizedLazyImpl – uses an object lock to ensure exclusive access during initialization.
SafePublicationLazyImpl – employs volatile fields and AtomicReferenceFieldUpdater.compareAndSet (CAS) to achieve thread‑safety without locking.
UnsafeLazyImpl – performs no synchronization; suitable only for single‑threaded contexts such as Android UI code.
The article explains why the initializer and the backing _value field are marked volatile , how synchronized guarantees visibility, and why volatile alone does not provide atomicity.
It also clarifies the concept of atomicity, illustrating the difference between simple assignments (atomic) and compound operations like a++ , which require CAS to avoid race conditions.
Practical recommendations are provided:
SYNCHRONIZED : use when strict single‑initialization is required and occasional blocking is acceptable.
PUBLICATION : prefer when multiple threads may call the initializer, accepting that the initializer might run more than once but only the first result is used.
NONE : suitable for main‑thread‑only scenarios such as Android Activity or Fragment fields.
Extended usage examples show how to apply lazy in a fragment‑bundle helper ( private val searchKey by bundles<SearchUserKey>() ) and in RecyclerView adapters using BaseQuickAdapter , demonstrating concise and elegant code.
The article concludes with references to external resources on Kotlin lazy, volatile vs. atomic operations, and the differences between AtomicReference and AtomicReferenceFieldUpdater .
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.