1 11 package org.eclipse.core.internal.preferences; 12 13 import org.eclipse.core.runtime.ListenerList; 14 15 21 public class ListenerRegistry { 22 23 26 private static class ListenerMap { 27 private static final int GROW_SIZE = 10; 28 String [] keys; 29 ListenerList[] values; 30 31 34 ListenerMap(int size) { 35 super(); 36 this.keys = new String [size]; 37 this.values = new ListenerList[size]; 38 } 39 40 44 ListenerList get(String key) { 45 if (key == null) 46 throw new NullPointerException (); 47 for (int i = 0; i < keys.length; i++) 48 if (key.equals(keys[i])) 49 return values[i]; 50 return null; 51 } 52 53 57 void put(String key, ListenerList value) { 58 if (key == null) 59 throw new NullPointerException (); 60 if (value == null) { 61 remove(key); 62 return; 63 } 64 int emptyIndex = -1; 66 for (int i = 0; i < keys.length; i++) { 67 String existing = keys[i]; 68 if (existing == null) { 69 emptyIndex = i; 70 continue; 71 } 72 if (existing.equals(key)) { 73 values[i] = value; 74 return; 75 } 76 } 77 if (emptyIndex == -1) 78 emptyIndex = grow(); 79 keys[emptyIndex] = key; 80 values[emptyIndex] = value; 81 } 82 83 86 private int grow() { 87 int size = keys.length; 88 String [] tempKeys = new String [size + GROW_SIZE]; 89 System.arraycopy(keys, 0, tempKeys, 0, size); 90 keys = tempKeys; 91 ListenerList[] tempValues = new ListenerList[size + GROW_SIZE]; 92 System.arraycopy(values, 0, tempValues, 0, size); 93 values = tempValues; 94 return size; 95 } 96 97 104 void remove(String key) { 105 if (key == null) 106 throw new NullPointerException (); 107 for (int i = 0; i < keys.length; i++) 108 if (key.equals(keys[i])) { 109 keys[i] = null; 110 values[i] = null; 111 return; 112 } 113 } 114 } 115 116 static final Object [] EMPTY_LIST = new Object [0]; 117 ListenerMap registry = new ListenerMap(25); 118 119 122 public synchronized Object [] getListeners(String path) { 123 ListenerList list = registry.get(path); 124 return list == null ? EMPTY_LIST : list.getListeners(); 125 } 126 127 131 public synchronized void add(String path, Object listener) { 132 ListenerList list = registry.get(path); 133 if (list == null) 134 list = new ListenerList(ListenerList.IDENTITY); 135 list.add(listener); 136 registry.put(path, list); 137 } 138 139 143 public synchronized void remove(String path, Object listener) { 144 ListenerList list = registry.get(path); 145 if (list == null) 146 return; 147 list.remove(listener); 148 if (list.isEmpty()) 149 registry.remove(path); 150 } 151 152 155 public synchronized void clear(String path) { 156 registry.remove(path); 157 } 158 159 } 160 | Popular Tags |