1 /*******************************************************************************
\r
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
\r
3 * in Industry THTH ry.
\r
4 * All rights reserved. This program and the accompanying materials
\r
5 * are made available under the terms of the Eclipse Public License v1.0
\r
6 * which accompanies this distribution, and is available at
\r
7 * http://www.eclipse.org/legal/epl-v10.html
\r
10 * VTT Technical Research Centre of Finland - initial API and implementation
\r
11 *******************************************************************************/
\r
12 package fi.vtt.simantics.procore.internal;
\r
14 import java.lang.reflect.Array;
\r
17 * ListenerList is an efficient and synchronized list of listeners.
\r
18 * The class is optimized for quick getListeners and slow add/remove.
\r
20 * @author Toni Kalajainen
\r
22 public class ListenerList<T> {
\r
25 * Array of listeners
\r
27 private volatile T [] array;
\r
32 private final Class<T> componentType;
\r
35 * Construct new Listener List
\r
36 * @param componentType the class of the listener type
\r
38 public ListenerList(Class<T> componentType)
\r
40 this.componentType = componentType;
\r
41 array = createArray(0);
\r
44 public T[] getListeners()
\r
49 public synchronized void add(T listener)
\r
51 int oldLength = array.length;
\r
52 int newLength = oldLength + 1;
\r
53 T newArray[] = createArray(newLength);
\r
54 System.arraycopy(array, 0, newArray, 0, oldLength);
\r
55 newArray[oldLength] = listener;
\r
60 * Removes the first occurance of listener.
\r
61 * If the listener is added multiple times, then it must be removed
\r
64 * @param listener a listener
\r
65 * @return the listener that was removed from the list
\r
67 public synchronized boolean remove(T listener)
\r
69 int pos = getPos(listener);
\r
70 if (pos<0) return false;
\r
72 int oldLength = array.length;
\r
73 int newLength = oldLength -1;
\r
74 T newArray[] = createArray(newLength);
\r
78 System.arraycopy(array, 0, newArray, 0, pos);
\r
82 System.arraycopy(array, pos+1, newArray, pos, newLength-pos);
\r
88 private synchronized int getPos(T listener)
\r
90 for (int i=0; i<array.length; i++)
\r
91 if (array[i] == listener)
\r
98 return array.length;
\r
101 public boolean isEmpty()
\r
103 return array.length == 0;
\r
106 public void clear()
\r
108 array = createArray(0);
\r
111 @SuppressWarnings("unchecked")
\r
112 private T[] createArray(int size)
\r
114 return (T[]) Array.newInstance(componentType, size);
\r