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