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