lazy

We wrote a version of a lazily initialized property in the previous section. The standard library has a better version of a delegate property for delaying object creation. An instance of the lazy interface is produced with the lazy function:

val str by lazy { "I'm lazily initialized" }

The lazy function can accept also a LazyThreadSafetyMode enum, which has three values:

  • If you don’t specify a value from this enum, SYNCHRONIZED will be used. This is a thread-safe mode and uses synchronization for thread safety.
  • The PUBLICATION mode can be accessed by multiple concurrent callers, but the value from the first accessor will be returned.
  • The NONE mode is not thread safe and should be used only when you are sure that only one thread will be accessing the delegate property.

The following code includes the preceding three values:

public enum class LazyThreadSafetyMode {

/**
* Locks are used to ensure that only a single thread can initialize the [Lazy] instance.
*/
SYNCHRONIZED,

/**
* Initializer function can be called several times on concurrent access to uninitialized [Lazy] instance value,
* but only the first returned value will be used as the value of [Lazy] instance.
*/
PUBLICATION,

/**
* No locks are used to synchronize an access to the [Lazy] instance value; if the instance is accessed from multiple threads, its behavior is undefined.
*
* This mode should not be used unless the [Lazy] instance is guaranteed never to be initialized from more than one thread.
*/
NONE,
}

 

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.3.43