2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.util;
11 import java.util.Collections;
12 import java.util.EventListener;
14 import java.util.concurrent.ConcurrentHashMap;
15 import java.util.concurrent.ConcurrentMap;
16 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
17 import org.opendaylight.yangtools.concepts.ListenerRegistration;
20 public class ListenerRegistry<T extends EventListener> implements Iterable<ListenerRegistration<T>> {
22 private final ConcurrentMap<ListenerRegistration<? extends T>,ListenerRegistration<? extends T>> listeners;
23 final Set<ListenerRegistration<T>> unmodifiableView;
25 @SuppressWarnings("unchecked")
26 public ListenerRegistry() {
27 listeners = new ConcurrentHashMap<>();
28 // This conversion is known to be safe.
29 @SuppressWarnings("rawtypes")
30 final Set rawSet = Collections.unmodifiableSet(listeners.keySet());
31 unmodifiableView = rawSet;
34 public Iterable<ListenerRegistration<T>> getListeners() {
35 return unmodifiableView;
38 public ListenerRegistration<T> register(final T listener) {
39 if (listener == null) {
40 throw new IllegalArgumentException("Listener should not be null.");
42 final ListenerRegistrationImpl<T> ret = new ListenerRegistrationImpl<>(listener);
43 listeners.put(ret,ret);
47 public <L extends T> ListenerRegistration<L> registerWithType(final L listener) {
48 final ListenerRegistrationImpl<L> ret = new ListenerRegistrationImpl<>(listener);
49 listeners.put(ret,ret);
54 public java.util.Iterator<ListenerRegistration<T>> iterator() {
55 return unmodifiableView.iterator();
58 @SuppressWarnings("rawtypes")
59 private void remove(final ListenerRegistrationImpl registration) {
60 listeners.remove(registration);
63 private class ListenerRegistrationImpl<P extends EventListener> extends AbstractObjectRegistration<P> implements
64 ListenerRegistration<P> {
66 public ListenerRegistrationImpl(final P instance) {
71 protected void removeRegistration() {
72 ListenerRegistry.this.remove(this);
76 public static <T extends EventListener> ListenerRegistry<T> create() {
77 return new ListenerRegistry<>();