Copyright 2011, Randy Strauss>

Delayed Computation

A friend was sent this interview question. I haven't typed it into eclipse, or otherwise compiled it...

Provide an alternate implementation of the following class (a delayed computation class) that uses no conditional logic. For extra credit, make it thread-safe.

Note: if, while/do, switch/case and the ? operator count as conditional logic.

 
abstract class DoLater {
    private boolean evaluated;
    private T value;
    public T get() {
        if (!evaluated) {
            value = compute();
            evaluated = true;
        }
        return value;
    }
    abstract protected T compute();
}

Instead of conditional logic, what can we do?
During construction, we could make a sub-object that does the computation. When get() is called, it can call the object to do the computation and then assign an object that does no computation...

I'd have to look up the Java and/or use Eclipse to get the syntax, but something like:

 
abstract class DoLater {
    class DoItNow {
        void get() { // don't sync here- or the 2nd will eventually get in!
	     value = compute();
	     doit = new StopDoing;
        }
    }
    class StopDoing extends DoItNow {
        void get() {
        }
    }

    private T value;
    private DoItNow doit = new DoItNow(); 

    public T get() {
        synchronize(doit) {  // synchronize keeps multiple threads out
	    doit.doit();     // could sync on "this", too...
        }
        return value;
    }
    abstract protected T compute();
}


Copyright 2011, Randy Strauss>