| 16 | import java.util.concurrent.locks.ReentrantLock; |
| 17 | |
| 18 | public class Delay implements IDeref, IPending{ |
| 19 | Object val; |
| 20 | Throwable exception; |
| 21 | IFn fn; |
| 22 | volatile Lock lock; |
| 23 | |
| 24 | public Delay(IFn f){ |
| 25 | fn = f; |
| 26 | val = null; |
| 27 | exception = null; |
| 28 | lock = new ReentrantLock(); |
| 29 | } |
| 30 | |
| 31 | static public Object force(Object x) { |
| 32 | return (x instanceof Delay) ? |
| 33 | ((Delay) x).deref() |
| 34 | : x; |
| 35 | } |
| 36 | |
| 37 | private void realize() { |
| 38 | Lock l = lock; |
| 39 | if(l != null) { |
| 40 | l.lock(); |
| 41 | try { |
| 42 | if(fn!=null) { |
| 43 | try { |
| 44 | val = fn.invoke(); |
| 45 | } catch (Throwable t) { |
| 46 | exception = t; |
| 47 | } |
| 48 | fn = null; |
| 49 | lock = null; |
| 50 | } |
| 51 | } finally { |
| 52 | l.unlock(); |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | public Object deref() { |
| 58 | if(lock != null) |
| 59 | realize(); |
| 60 | if(exception != null) |
| 61 | throw Util.sneakyThrow(exception); |
| 62 | return val; |
| 63 | } |
| 64 | |
| 65 | public boolean isRealized(){ |
| 66 | return lock == null; |
| 67 | } |
| 68 | } |
nothing calls this directly
no outgoing calls
no test coverage detected