Lazy<T> and memoizers

Mike Duigou mike.duigou at oracle.com
Wed Sep 26 10:15:19 PDT 2012


Any reason not to use AtomicReference as your Holder?

Mike

On Sep 26 2012, at 05:53 , Aleksey Shipilev wrote:

> 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;
>   }
> 
>   @Override
>   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?
> 
> -Aleksey.



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