Brian's Waste of Time

Sun, 09 Jan 2005

Futures 3: Transparent Futures in Java

After looking at futures in Java, then transparent ones in Ruby, adding transparent futures in Java turned out to be pretty simple as well. Just added this method to the two evaluators (duplication bad, yes, but I don't feel like making a new factory dependent on an Evaluator, so =P):

public Object promise(Class k, Expression e) {
    final Future f = this.promise(e);
    return Proxy.newProxyInstance(k.getClassLoader(), new Class[] {k}, new InvocationHandler()
    {
        public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
            return method.invoke(f.getResult(), objects);
        }
    });
}

Used like:

public void testSomething() throws Exception {
    final boolean called[] = { false };
    final Map map = (Map) lazy.promise(Map.class, new Expression() {
        public Object evaluate() throws Exception {
            called[0] = true;
            final Map map = new HashMap();
            map.put("a", "A");
            return map;
        }
    });

    assertEquals("A", map.get("a"));
    assertTrue(called[0]);
}

This only works by interfaces, but using AWProxy instead would be trivial =) If Apple would let me have a 1.5 JDK I might use generics instead, but alas...

Now, async and lazy futures are fun and all, but I think it is time to stop looking at how to implement and look at how to use.

1 writebacks [/src/java] permanent link