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
15 package org.simantics.utils.datastructures;
\r
17 import java.lang.reflect.Array;
\r
19 import org.simantics.utils.threads.SyncListenerList;
\r
22 * ListenerList is an efficient and synchronized list of listeners.
\r
23 * The class is optimized for quick getListeners and slow add/remove.
\r
25 * @see SyncListenerList for thread context switching listener list impl
\r
27 * @author Toni Kalajainen
\r
30 public class ListenerList<T> {
\r
33 * Array of listeners
\r
35 private volatile T [] array;
\r
40 private final Class<T> componentType;
\r
43 * Construct new Listener List
\r
44 * @param componentType the class of the listener type
\r
46 public ListenerList(Class<T> componentType)
\r
48 this.componentType = componentType;
\r
49 array = createArray(0);
\r
52 public T[] getListeners()
\r
57 public synchronized void add(T listener)
\r
59 int oldLength = array.length;
\r
60 int newLength = oldLength + 1;
\r
61 T newArray[] = createArray(newLength);
\r
62 System.arraycopy(array, 0, newArray, 0, oldLength);
\r
63 newArray[oldLength] = listener;
\r
68 * Removes the first occurance of listener.
\r
69 * If the listener is added multiple times, then it must be removed
\r
72 * @param listener a listener
\r
73 * @return the listener that was removed from the list
\r
75 public synchronized boolean remove(T listener)
\r
77 int pos = getPos(listener);
\r
78 if (pos<0) return false;
\r
80 int oldLength = array.length;
\r
81 int newLength = oldLength -1;
\r
82 T newArray[] = createArray(newLength);
\r
86 System.arraycopy(array, 0, newArray, 0, pos);
\r
90 System.arraycopy(array, pos+1, newArray, pos, newLength-pos);
\r
96 private synchronized int getPos(T listener)
\r
98 for (int i=0; i<array.length; i++)
\r
99 if (array[i] == listener)
\r
106 return array.length;
\r
109 public boolean isEmpty()
\r
111 return array.length == 0;
\r
114 public void clear()
\r
116 array = createArray(0);
\r
119 @SuppressWarnings("unchecked")
\r
120 private T[] createArray(int size)
\r
122 return (T[]) Array.newInstance(componentType, size);
\r