1 13 14 package EDU.oswego.cs.dl.util.concurrent; 15 import java.util.*; 16 17 37 38 39 public class ObservableSync implements Sync { 40 41 42 45 public interface SyncObserver { 46 49 50 public void onAcquire(Object arg); 51 52 55 public void onRelease(Object arg); 56 } 57 58 protected final CopyOnWriteArraySet observers_ = new CopyOnWriteArraySet(); 59 protected Object arg_; 60 61 66 67 public ObservableSync(Object notificationArgument) { 68 arg_ = notificationArgument; 69 } 70 71 74 public synchronized Object getNotificationArgument() { 75 return arg_; 76 } 77 78 82 83 public synchronized Object setNotificationArgument(Object notificationArg) { 84 Object old = arg_; 85 arg_ = notificationArg; 86 return old; 87 } 88 89 90 91 public void acquire() { 92 Object arg = getNotificationArgument(); 93 for (Iterator it = observers_.iterator(); it.hasNext(); ) { 94 ((SyncObserver)it.next()).onAcquire(arg); 95 } 96 } 97 98 public boolean attempt(long msecs) { 99 acquire(); 100 return true; 101 } 102 103 public void release() { 104 Object arg = getNotificationArgument(); 105 for (Iterator it = observers_.iterator(); it.hasNext(); ) { 106 ((SyncObserver)it.next()).onRelease(arg); 107 } 108 } 109 110 111 112 113 public void attach(SyncObserver obs) { 114 observers_.add(obs); 115 } 116 117 118 public void detach(SyncObserver obs) { 119 observers_.remove(obs); 120 } 121 122 125 126 public Iterator observers() { 127 return observers_.iterator(); 128 } 129 130 131 } 132 133 134 | Popular Tags |