Caching using Supplier Java 8

Viewed 3069

This method, as I know, memorizes (caches) the value of supplier that passed as the parameter. As I understand It behaves like singleton pattern. Can anyone explain how it works?

  public static <T> Supplier<T> memoize(final Supplier<? extends T> valueSupplier)
  {
    final List<T> memoryList= new ArrayList<>();
    return () -> {
      if (memoryList.isEmpty()) {
        memoryList.add(valueSupplier.get());
      }
      return memoryList.get(0);
    };
  }

Usage like this:

Supplier<SomeClass> cachedValue = memoize(() -> someClassObject.getSomeValueToBeCached());
cachedValue.get().doMethod();
2 Answers
Related