| 19 | import java.util.concurrent.locks.ReentrantLock; |
| 20 | |
| 21 | public final class LazySeq extends Obj implements ISeq, Sequential, List, IPending, IHashEq{ |
| 22 | |
| 23 | private static final long serialVersionUID = -7531333024710395876L; |
| 24 | |
| 25 | private transient IFn fn; |
| 26 | private Object sv; |
| 27 | private ISeq s; |
| 28 | private volatile Lock lock; |
| 29 | |
| 30 | public LazySeq(IFn f){ |
| 31 | fn = f; |
| 32 | lock = new ReentrantLock(); |
| 33 | } |
| 34 | |
| 35 | private LazySeq(IPersistentMap meta, ISeq seq){ |
| 36 | super(meta); |
| 37 | fn = null; |
| 38 | s = seq; |
| 39 | } |
| 40 | |
| 41 | public Obj withMeta(IPersistentMap meta){ |
| 42 | if(meta() == meta) |
| 43 | return this; |
| 44 | return new LazySeq(meta, seq()); |
| 45 | } |
| 46 | |
| 47 | // MUST be locked when called! |
| 48 | final private void force() { |
| 49 | if (fn != null) { |
| 50 | sv = fn.invoke(); |
| 51 | fn = null; |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | final private Object sval() { |
| 56 | Lock l = lock; |
| 57 | if(l != null) { |
| 58 | l.lock(); |
| 59 | try { |
| 60 | //must re-examine under lock |
| 61 | if(lock != null) { //unrealized |
| 62 | force(); |
| 63 | return sv; |
| 64 | } |
| 65 | } finally { |
| 66 | l.unlock(); |
| 67 | } |
| 68 | } |
| 69 | // realized, read of lock above guarantees visibility of s |
| 70 | return s; |
| 71 | } |
| 72 | |
| 73 | final private Object unwrap(Object ls){ |
| 74 | while(ls instanceof LazySeq) { |
| 75 | ls = ((LazySeq) ls).sval(); |
| 76 | } |
| 77 | return ls; |
| 78 | } |
nothing calls this directly
no outgoing calls
no test coverage detected