1 8 9 15 package jfun.yan.lifecycle; 16 17 import java.io.Serializable ; 18 import java.util.Collection ; 19 import java.util.Collections ; 20 import java.util.Iterator ; 21 import java.util.LinkedHashMap ; 22 import java.util.Map ; 23 import java.util.Set ; 24 25 34 public class Lifecycle implements Life, Serializable { 35 private final Map entries = new LinkedHashMap (); 36 40 public static class Entry implements Serializable { 41 private final Procedure proc; 42 private final boolean reentrant; 43 50 public Entry(Procedure proc, boolean reentrant) { 51 this.proc = proc; 52 this.reentrant = reentrant; 53 } 54 57 public Procedure getProcedure() { 58 return proc; 59 } 60 63 public boolean isReentrant() { 64 return reentrant; 65 } 66 public boolean equals(Object obj) { 67 if(obj instanceof Entry){ 68 Entry other = (Entry)obj; 69 return reentrant==other.reentrant && proc.equals(other.proc); 70 } 71 else return false; 72 } 73 public int hashCode() { 74 return reentrant?1:0+proc.hashCode()*31; 75 } 76 public String toString() { 77 return proc.toString(); 78 } 79 } 80 83 public boolean isEmpty(){ 84 return entries.isEmpty(); 85 } 86 89 public int size(){ 90 return entries.size(); 91 } 92 98 public void put(Object key, Procedure proc, boolean reentrant){ 99 entries.put(key, new Entry(proc, reentrant)); 100 } 101 105 public void remove(Object key){ 106 entries.remove(key); 107 } 108 113 public Entry get(Object key){ 114 return (Entry)entries.get(key); 115 } 116 119 public Set keys(){ 120 return entries.keySet(); 121 } 122 125 public Collection entries(){ 126 return Collections.unmodifiableCollection(entries.values()); 127 } 128 public LiveObject bear(Object obj){ 129 final Map invokables = new LinkedHashMap (entries.size()); 130 for(Iterator it=entries.keySet().iterator(); it.hasNext();){ 131 final Object key = it.next(); 132 final Entry entry = get(key); 133 final Procedure proc = entry.getProcedure(); 134 invokables.put(key, entry.isReentrant()?proc:new NonReentrantProc(proc)); 135 } 136 return new LiveObject(obj, invokables); 137 } 138 private static class NonReentrantProc implements Procedure{ 139 public synchronized void invoke(Object self, Object [] args) throws Throwable { 140 if(visited) 141 return; 142 visited = true; 143 proc.invoke(self, args); 144 } 145 public String toString() { 146 return proc.toString(); 147 } 148 private final Procedure proc; 149 private boolean visited = false; 150 NonReentrantProc(Procedure proc) { 151 this.proc = proc; 152 } 153 } 154 } 155 | Popular Tags |