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 org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
16 import org.opendaylight.yangtools.concepts.ListenerRegistration;
19 public class ListenerRegistry<T extends EventListener> implements Iterable<ListenerRegistration<T>> {
21 private final ConcurrentHashMap<ListenerRegistration<? extends T>,ListenerRegistration<? extends T>> listeners;
22 final Set<ListenerRegistration<T>> unmodifiableView;
24 @SuppressWarnings("unchecked")
25 public ListenerRegistry() {
26 listeners = new ConcurrentHashMap<>();
27 // This conversion is known to be safe.
28 @SuppressWarnings("rawtypes")
29 final Set rawSet = Collections.unmodifiableSet(listeners.keySet());
30 unmodifiableView = rawSet;
33 public Iterable<ListenerRegistration<T>> getListeners() {
34 return unmodifiableView;
37 public ListenerRegistration<T> register(T listener) {
38 if (listener == null) {
39 throw new IllegalArgumentException("Listener should not be null.");
41 ListenerRegistrationImpl<T> ret = new ListenerRegistrationImpl<T>(listener);
42 listeners.put(ret,ret);
46 public <L extends T> ListenerRegistration<L> registerWithType(L listener) {
47 ListenerRegistrationImpl<L> ret = new ListenerRegistrationImpl<L>(listener);
48 listeners.put(ret,ret);
53 public java.util.Iterator<ListenerRegistration<T>> iterator() {
54 return unmodifiableView.iterator();
57 @SuppressWarnings("rawtypes")
58 private void remove(ListenerRegistrationImpl registration) {
59 listeners.remove(registration);
62 private class ListenerRegistrationImpl<P extends EventListener> //
63 extends AbstractObjectRegistration<P> //
64 implements ListenerRegistration<P> {
66 public ListenerRegistrationImpl(P instance) {
71 protected void removeRegistration() {
72 ListenerRegistry.this.remove(this);
76 public static <T extends EventListener> ListenerRegistry<T> create() {
77 return new ListenerRegistry<>();