From 59ff9dc3cfcf4ce6fde08856e1aa83a0a9d3978c Mon Sep 17 00:00:00 2001 From: Ilya Gorbunov Date: Mon, 15 Jun 2015 18:11:48 +0300 Subject: [PATCH] Document lazy interface and methods. --- libraries/stdlib/src/kotlin/util/Lazy.kt | 26 +++++++++++++++++++-- libraries/stdlib/src/kotlin/util/LazyJVM.kt | 5 ++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/libraries/stdlib/src/kotlin/util/Lazy.kt b/libraries/stdlib/src/kotlin/util/Lazy.kt index 4ab30c48870..585c0c2bcd1 100644 --- a/libraries/stdlib/src/kotlin/util/Lazy.kt +++ b/libraries/stdlib/src/kotlin/util/Lazy.kt @@ -1,17 +1,39 @@ package kotlin - +/** + * Represents a value with lazy initialization. + */ public interface Lazy { + /** Gets the lazily initialized value of the current Lazy instance. */ public val value: T + /** Returns `true` if a value for this Lazy instance has been already initialized. */ public val valueCreated: Boolean } +/** + * An extension to delegate a read-only property of type [T] to an instance of [Lazy]. + * + * This extension allows to use instances of Lazy for property delegation: + * `val property: String by lazy { initializer }` + */ public fun Lazy.get(thisRef: Any?, property: PropertyMetadata): T = value - +/** + * Specifies how a [Lazy] instance synchronizes access among multiple threads. + */ public enum class LazyThreadSafetyMode { + + /** + * Locks are used to ensure that only a single thread can initialize the [Lazy] instance. + */ SYNCHRONIZED, + + /** + * No locks are used to synchronize the access to the [Lazy] instance value; if the instance is accessed from multiple threads, its behavior is undefined. + * + * This mode should be used only when high performance is crucial and the [Lazy] instance is guaranteed never to be initialized from more than one thread. + */ NONE, } diff --git a/libraries/stdlib/src/kotlin/util/LazyJVM.kt b/libraries/stdlib/src/kotlin/util/LazyJVM.kt index ca138db7bc6..b6f23a7815d 100644 --- a/libraries/stdlib/src/kotlin/util/LazyJVM.kt +++ b/libraries/stdlib/src/kotlin/util/LazyJVM.kt @@ -1,7 +1,12 @@ package kotlin +/** Initializes a new instance of the [Lazy] that uses the specified initialization function [initializer] + * and the default thread-safety [LazyThreadSafetyMode.SYNCHRONIZED]. */ public fun lazy(initializer: () -> T): Lazy = LazyImpl(initializer, Any()) + +/** Initializes a new instance of the [Lazy] that uses the specified initialization function [initializer] + * and thread-safety [mode]. */ public fun lazy(mode: LazyThreadSafetyMode, initializer: () -> T): Lazy = when (mode) { LazyThreadSafetyMode.SYNCHRONIZED -> LazyImpl(initializer, Any())