Lazy<T> and memoizers

Aleksey Shipilev aleksey.shipilev at
Wed Sep 26 05:53:53 PDT 2012

Hi guys,

Another thing we've been discussing internally was the library support
for memoization. Having the Lazy<T> class would be nice to provide
shortcut for memoizing lambda expressions, somewhat similar to C#-ish
Lazy<T>, i.e.:

class Lazy<T> implements Factory<T> {

   public <N> static Lazy<N> of(Factory<N> f) {
       return new Lazy<N>(f);

   private final Factory<T> f;
   private volatile Holder<T> holder;

   public Lazy(Factory<T> f) {
       this.f = f;

   public T make() {
       if (holder == null) {
           T t = f.make();
           CAS(holder, null, new Holder(t));
       return holder.value;

   static class Holder<T> {
       public final T value;
       public Holder(T t) { value = t; }


There is an open question if we want to make sure f.make() is executed
once (this example code does not guarantee that, and guaranteeing would
require some sort of locking, so I wonder if this belongs in jsr166
additions), but we can spin another class for that.

Then, we can do something like:

  foo(Factory<T> f);
  foo(Lazy.of(() -> new MyHeavyAndBoringObject());

...or even use that to simulate call-by-need in specific places.

I'm sure something like that was already considered, is there a history
on deciding if this is viable and needed?


More information about the lambda-libs-spec-observers mailing list