1 package gnu.mapping; 2 3 public class RunnableClosure implements Runnable 4 { 5 Object result; 6 CallContext context; 7 public Environment environment; 8 9 private InPort in; 14 private OutPort out; 15 private OutPort err; 16 Throwable exception; 17 18 Procedure action; 19 String name; 20 21 static int nrunnables=0; 22 23 public String getName() { 24 return name; 25 } 26 27 public void setName(String name) { 28 this.name=name; 29 } 30 31 public RunnableClosure (Procedure action, CallContext parentContext) 32 { 33 this(action, parentContext, parentContext.getEnvironment()); 34 } 35 36 public RunnableClosure (Procedure action, 37 CallContext parentContext, Environment penvironment) 38 { 39 setName("r"+nrunnables++); 40 this.action = action; 41 SimpleEnvironment env = Environment.make(getName(), penvironment); 42 env.flags |= Environment.THREAD_SAFE; 43 env.flags &= ~Environment.DIRECT_INHERITED_ON_SET; 44 this.environment = env; 45 int n = parentContext.pushedFluidsCount; 46 for (int i = 0; i < n; i++) 47 { 48 Location loc = parentContext.pushedFluids[i]; 53 Symbol name = loc.getKeySymbol(); 54 Object property = loc.getKeyProperty(); 55 if (name != null && loc instanceof NamedLocation) 56 { 57 NamedLocation nloc = (NamedLocation) loc; 58 if (nloc.base == null) 59 { 60 SharedLocation sloc = new SharedLocation(name, property, 0); 61 sloc.value = nloc.value; 62 nloc.base = sloc; 63 nloc.value = null; 64 nloc = sloc; 65 } 66 int hash = name.hashCode() ^ System.identityHashCode(property); 67 NamedLocation xloc = env.addUnboundLocation(name, property, hash); 68 xloc.base = nloc; 69 } 70 } 71 } 72 73 public RunnableClosure (Procedure action, Environment penvironment, 74 InPort in, OutPort out, OutPort err) 75 { 76 this(action, CallContext.getInstance(), penvironment); 77 this.in = in; 78 this.out = out; 79 this.err = err; 80 } 81 82 public RunnableClosure (Procedure action) 83 { 84 this(action, CallContext.getInstance()); 85 } 86 87 88 public final CallContext getCallContext() { return context; } 89 90 public void run () 91 { 92 try 93 { 94 if (context == null) 95 context = CallContext.getInstance(); 96 else 97 CallContext.setInstance(context); 98 context.curEnvironment = environment; 99 if (in != null) 100 InPort.setInDefault(in); 101 if (out != null) 102 OutPort.setOutDefault(out); 103 if (err != null) 104 OutPort.setErrDefault(err); 105 result = action.apply0 (); 106 } 107 catch (Throwable ex) 108 { 109 exception = ex; 110 } 111 } 112 113 116 Object getResult () throws Throwable 117 { 118 Throwable ex = exception; 119 if (ex != null) 120 throw ex; 121 return result; 122 } 123 124 public String toString() { 125 StringBuffer buf = new StringBuffer (); 126 buf.append ("#<runnable "); 127 buf.append(getName()); 128 buf.append(">"); 129 return buf.toString(); 130 } 131 } 132 | Popular Tags |