Class ConcurrentLazy<T>

java.lang.Object
org.litebridge.commons.type.ConcurrentLazy<T>
Type Parameters:
T - the type of the lazily initialized value

public final class ConcurrentLazy<T> extends Object
A thread-safe, lazily initialized value holder that allows resetting the value.

This class ensures that the value is initialized only once, using the provided Supplier, and that subsequent calls to optional() or orNull() return the cached value.

The value can be reset using reset(), which clears the cached value and allows it to be recomputed on the next access.

  • Constructor Details

    • ConcurrentLazy

      public ConcurrentLazy(Supplier<T> initializer)
      Constructs a new ResettableLazy with the given initializer.
      Parameters:
      initializer - a Supplier that provides the value when it is first needed
      Throws:
      NullPointerException - if the initializer is null
  • Method Details

    • optional

      public Optional<T> optional()
      The primary accessor. Returns the value wrapped in an Optional.
      Returns:
      the value wrapped in an Optional
    • orThrow

      public T orThrow()
      Returns the value, or throws a NoSuchElementException if the value is null.
      Returns:
      the value
      Throws:
      NoSuchElementException - if the value is null
    • orThrow

      public <X extends Exception> T orThrow(Supplier<X> exceptionSupplier) throws X
      Returns the value, or throws an exception provided by the supplier if the value is null.
      Type Parameters:
      X - the type of the exception to be thrown
      Parameters:
      exceptionSupplier - the supplier of the exception to be thrown
      Returns:
      the value
      Throws:
      X - if the value is null
    • orNull

      public @Nullable T orNull()
      Returns the lazily initialized value. If the value has not yet been initialized, it will be computed using the provided initializer in a thread-safe manner.
      Returns:
      the initialized value
    • peek

      public @Nullable T peek()
      Returns the current value without triggering initialization. Useful for logging or debugging where you don't want to force a side-effect.
      Returns:
      the current value, or null if not yet initialized
    • reset

      public void reset()
      Resets the cached value, allowing it to be recomputed on the next call to optional() or orNull(). This method is thread-safe.
    • isInitialised

      public boolean isInitialised()
      Returns true if the value has already been initialised, or false otherwise.
      Returns:
      true if the value is initialised; false if it is still uninitialised