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 *******************************************************************************/
15 package org.simantics.utils.threads.internal;
17 import java.lang.reflect.Array;
20 * ListenerList is an efficient and synchronized list of listeners.
21 * The class is optimized for quick getListeners and slow add/remove.
23 * @author Toni Kalajainen
25 public class ListenerList<T> {
30 private volatile T [] array;
35 private final Class<T> componentType;
38 * Construct new Listener List
39 * @param componentType the class of the listener type
41 public ListenerList(Class<T> componentType)
43 this.componentType = componentType;
44 array = createArray(0);
47 public T[] getListeners()
52 public synchronized void add(T listener)
54 int oldLength = array.length;
55 int newLength = oldLength + 1;
56 T newArray[] = createArray(newLength);
57 System.arraycopy(array, 0, newArray, 0, oldLength);
58 newArray[oldLength] = listener;
63 * Removes the first occurance of listener.
64 * If the listener is added multiple times, then it must be removed
67 * @param listener a listener
68 * @return the listener that was removed from the list
70 public synchronized boolean remove(T listener)
72 int pos = getPos(listener);
73 if (pos<0) return false;
75 int oldLength = array.length;
76 int newLength = oldLength -1;
77 T newArray[] = createArray(newLength);
81 System.arraycopy(array, 0, newArray, 0, pos);
85 System.arraycopy(array, pos+1, newArray, pos, newLength-pos);
91 private synchronized int getPos(T listener)
93 for (int i=0; i<array.length; i++)
94 if (array[i] == listener)
104 public boolean isEmpty()
106 return array.length == 0;
111 array = createArray(0);
114 @SuppressWarnings("unchecked")
115 private T[] createArray(int size)
117 return (T[]) Array.newInstance(componentType, size);