KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > kawa > lang > Promise


1 package kawa.lang;
2 import gnu.mapping.*;
3 import gnu.text.Printable;
4 import gnu.lists.Consumer;
5
6 /** Implement Scheme "promises".
7  * @author Per Bothner
8  */

9
10 public class Promise implements Printable
11 {
12   Procedure thunk;
13
14   /** The result - or null if it is not ready. */
15   Object JavaDoc result;
16
17   /** Create a new Promise that will evaluate thunk when forced. */
18   public Promise (Procedure thunk)
19   {
20     this.thunk = thunk;
21   }
22
23   public Object JavaDoc force () throws Throwable JavaDoc
24   {
25     if (result == null)
26       {
27     Object JavaDoc x = thunk.apply0 ();
28     if (result == null)
29       result = x;
30       }
31     return result;
32   }
33
34   public void print (Consumer out)
35   {
36     if (result == null)
37       out.write("#<promise - not forced yet>");
38     else
39       {
40     out.write("#<promise - forced to a ");
41     out.write(result.getClass().getName());
42     out.write ('>');
43       }
44   }
45 }
46
Popular Tags