1 7 package com.ibm.icu.impl; 8 9 import java.util.ArrayList ; 10 import java.util.EventListener ; 11 import java.util.Iterator ; 12 import java.util.LinkedList ; 13 import java.util.List ; 14 15 31 public abstract class ICUNotifier { 32 private final Object notifyLock = new Object (); 33 private NotifyThread notifyThread; 34 private List listeners; 35 36 43 public void addListener(EventListener l) { 44 if (l == null) { 45 throw new NullPointerException (); 46 } 47 48 if (acceptsListener(l)) { 49 synchronized (notifyLock) { 50 if (listeners == null) { 51 listeners = new ArrayList (5); 52 } else { 53 Iterator iter = listeners.iterator(); 55 while (iter.hasNext()) { 56 if (iter.next() == l) { 57 return; 58 } 59 } 60 } 61 62 listeners.add(l); 63 } 64 } else { 65 throw new IllegalStateException ("Listener invalid for this notifier."); 66 } 67 } 68 69 74 public void removeListener(EventListener l) { 75 if (l == null) { 76 throw new NullPointerException (); 77 } 78 synchronized (notifyLock) { 79 if (listeners != null) { 80 Iterator iter = listeners.iterator(); 82 while (iter.hasNext()) { 83 if (iter.next() == l) { 84 iter.remove(); 85 if (listeners.size() == 0) { 86 listeners = null; 87 } 88 return; 89 } 90 } 91 } 92 } 93 } 94 95 100 public void notifyChanged() { 101 if (listeners != null) { 102 synchronized (notifyLock) { 103 if (listeners != null) { 104 if (notifyThread == null) { 105 notifyThread = new NotifyThread(this); 106 notifyThread.setDaemon(true); 107 notifyThread.start(); 108 } 109 notifyThread.queue(listeners.toArray()); 110 } 111 } 112 } 113 } 114 115 118 private static class NotifyThread extends Thread { 119 private final ICUNotifier notifier; 120 private final List queue = new LinkedList (); 121 122 NotifyThread(ICUNotifier notifier) { 123 this.notifier = notifier; 124 } 125 126 129 public void queue(Object [] list) { 130 synchronized (this) { 131 queue.add(list); 132 notify(); 133 } 134 } 135 136 140 public void run() { 141 Object [] list; 142 while (true) { 143 try { 144 synchronized (this) { 145 while (queue.isEmpty()) { 146 wait(); 147 } 148 list = (Object [])queue.remove(0); 149 } 150 151 for (int i = 0; i < list.length; ++i) { 152 notifier.notifyListener((EventListener )list[i]); 153 } 154 } 155 catch (InterruptedException e) { 156 } 157 } 158 } 159 } 160 161 165 protected abstract boolean acceptsListener(EventListener l); 166 167 170 protected abstract void notifyListener(EventListener l); 171 } 172 | Popular Tags |