2 * ftw - AbstractListenerManager.java - Copyright © 2009 David Roden
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package net.pterodactylus.util.event;
20 import java.util.EventListener;
21 import java.util.List;
22 import java.util.concurrent.CopyOnWriteArrayList;
23 import java.util.concurrent.Executor;
25 import net.pterodactylus.util.thread.CurrentThreadExecutor;
28 * Abstract implementation of a listener support class. The listener support
29 * takes care of adding and removing {@link EventListener} implementations, and
30 * subclasses are responsible for firing appropriate events.
33 * The type of the source
35 * The type of the event listeners
36 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
38 public abstract class AbstractListenerManager<S, L extends EventListener> {
40 /** The source that emits the events. */
41 private final S source;
43 /** The list of listeners. */
44 private final List<L> listeners = new CopyOnWriteArrayList<L>();
46 /** Service that executes event threads. */
47 private final Executor executor;
50 * Creates a new listener support that emits events from the given source.
53 * The source of the events
55 public AbstractListenerManager(S source) {
56 this(source, new CurrentThreadExecutor());
60 * Creates a new listener support that emits events from the given source.
63 * The source of the events
65 * The executor used to fire events
67 public AbstractListenerManager(S source, Executor executor) {
69 this.executor = executor;
73 * Adds the given listener to the list of reigstered listeners.
78 public void addListener(L listener) {
79 synchronized (listeners) {
80 listeners.add(listener);
85 * Removes the given listener from the list of registered listeners.
88 * The listener to remove
90 public void removeListener(L listener) {
91 synchronized (listeners) {
92 listeners.remove(listener);
101 * Returns the source for the events.
103 * @return The event source
105 protected S getSource() {
110 * Returns the executor for the event firing.
112 * @return The executor
114 protected Executor getExecutor() {
119 * Returns a list of all registered listeners. The returned list is a copy
120 * of the original list so structural modifications will never occur when
121 * using the returned list.
123 * @return The list of all registered listeners
125 protected List<L> getListeners() {