Class Lazy<T>

java.lang.Object
de.team33.patterns.lazy.narvi.Lazy<T>
All Implemented Interfaces:
Supplier<T>

public final class Lazy<T> extends Object implements Supplier<T>
Implements a Supplier that provides a virtually fixed value. That value is only actually determined when it is accessed for the first time.

This implementation ensures that the originally defined initialization code is called at most once, even if there is concurrent access from multiple threads, unless the initialization attempt causes an (unchecked) exception.

Once the value is established, unnecessary effort to synchronize competing* read accesses is avoided.

*Pure read accesses are of course not really competing.

See Also:
  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Class
    Description
    static final class 
    Deprecated, for removal: This API element is subject to removal in a future version.
    use InitException instead!
  • Method Summary

    Modifier and Type
    Method
    Description
    final T
    get()
    Executes the originally defined initialization code once on the first call and returns its result on that and every subsequent call without executing the initialization code again.
    static <T> Lazy<T>
    init(Supplier<? extends T> initial)
    Returns a new instance giving a Supplier that defines the intended initialization of the represented value.
    static <T> Lazy<T>
    initEx(XSupplier<? extends T,?> initial)
    Returns a new instance giving an XSupplier that defines the intended initialization of the represented value.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Method Details

    • init

      public static <T> Lazy<T> init(Supplier<? extends T> initial)
      Returns a new instance giving a Supplier that defines the intended initialization of the represented value.
      Type Parameters:
      T - The result type of the initialisation code.
      See Also:
    • initEx

      public static <T> Lazy<T> initEx(XSupplier<? extends T,?> initial)
      Returns a new instance giving an XSupplier that defines the intended initialization of the represented value. The initialization code may throw a checked exception. If so, it is caught, wrapped in an Lazy.InitException, and rethrown.
      Type Parameters:
      T - The result type of the initialisation code.
      See Also:
    • get

      public final T get()
      Executes the originally defined initialization code once on the first call and returns its result on that and every subsequent call without executing the initialization code again. This method is thread safe.
      Specified by:
      get in interface Supplier<T>