Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implementing a lazy Supplier in java

What is the right paradigm or utility class (can't seem to find a preexisting class) to implement a lazy supplier in Java?

I want to have something that handles the compute-once/cache-later behavior and allows me to specify the computation behavior independently. I know this probably has an error but it has the right semantics:

abstract public class LazySupplier<T> implements Supplier<T> 
{
    private volatile T t;
    final private Object lock = new Object();

    final public T get() {
        if (t == null)
        {
            synchronized(lock)
            {
                if (t == null)
                    t = compute();
            }
        }
        return t;
    }
    abstract protected T compute();
}
like image 629
Jason S Avatar asked Dec 01 '12 20:12

Jason S


People also ask

How is lazy initialization implemented in Java?

You just create a field, annotate it with @Getter(lazy=true) and add initialization, like this: @Getter(lazy=true) private final Foo instance = new Foo();

Does Java support lazy evaluation?

Java supports lazy evaluation for the following specific syntax: The Boolean && and || operators, which will not evaluate their right operand when the left operand is false ( && ) or true ( || ).

What is lazy evaluation in Java?

Lazy evaluation is an evaluation strategy which delays the evaluation of an expression until its value is needed. The opposite of this is eager evaluation, where an expression is evaluated as soon as it is bound to a variable.[wikipedia]


2 Answers

This is already implemented in Suppliers.memoize method.

public static <T> Supplier<T> memoize(Supplier<T> delegate)

Returns a supplier which caches the instance retrieved during the first call to get() and returns that value on subsequent calls to get(). See: memoization

The returned supplier is thread-safe. The delegate's get() method will be invoked at most once. The supplier's serialized form does not contain the cached value, which will be recalculated when get() is called on the reserialized instance.

If delegate is an instance created by an earlier call to memoize, it is returned directly.

like image 113
Amir Raminfar Avatar answered Oct 19 '22 18:10

Amir Raminfar


Apache Commons Lang has a LazyInitializer.

like image 20
Stefan Birkner Avatar answered Oct 19 '22 20:10

Stefan Birkner