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