Monday, 26 November 2012

Java Lazy Evaluation

Lazy evaluation. This is where a piece of code is written which evaluates a value (usually requiring a relatively large amount of processing), but the code isn't executed until the moment it is needed (if ever).

For example, class A calls a method in class B. It passes some values (which take a long time to compute). If the values are passed lazily then class B can decide when and if to compute them. It is up to class A to implement the code for how to evaluate the value. So maybe there are 3 lazy values passed and class B decides it doesn't need to use value 1 but it does use values 2 and 3 (perhaps invoking each evaluation in separate threads, to maximise performance). The code to evaluate value 1 is never called, the code to evaluate values 2 and 3 will be called once and only once. Subsequent retrievals of a lazily evaluated value will return a cached copy of the value (unless the lazy evaluator is reset... see the code below).

Here is the class:

public abstract class Lazy<T>
  private boolean _evaluated = false;
  private T _value = null;

  public final T get()
    if (!_evaluated)
      _value = evaluate();
      _evaluated = true;

    return _value;

  public void reset()
    _evaluated = false;
    _value = null;

  protected abstract T evaluate();

... and here is how to use it:

  // Setup.
  final float height = 7.0f;

  // Create the lazy.
  Lazy<Float> halfHeight = new Lazy<Float>()
    public Float evaluate()
      return height / 2;

  // Get it's value.

And that's all you need. This code is completely free to use by anybody. It is held under the Do What You Want To Public License:

No comments:

Post a Comment