Updated toString for BI InstanceIdentifier
[yangtools.git] / concepts / src / main / java / org / opendaylight / yangtools / concepts / util / ListenerRegistry.java
1 package org.opendaylight.yangtools.concepts.util;
2
3 import java.util.Collections;
4 import java.util.EventListener;
5 import java.util.Set;
6 import java.util.concurrent.ConcurrentHashMap;
7
8 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
9 import org.opendaylight.yangtools.concepts.ListenerRegistration;
10
11 public class ListenerRegistry<T extends EventListener> implements Iterable<ListenerRegistration<T>> {
12
13     final ConcurrentHashMap<ListenerRegistration<T>,ListenerRegistration<T>> listeners;
14     final Set<ListenerRegistration<T>> unmodifiableView;
15
16     public ListenerRegistry() {
17         listeners = new ConcurrentHashMap<>();
18         unmodifiableView = Collections.unmodifiableSet(listeners.keySet());
19     }
20
21     public Iterable<ListenerRegistration<T>> getListeners() {
22         return unmodifiableView;
23     }
24
25     public ListenerRegistration<T> register(T listener) {
26         if (listener == null) {
27             throw new IllegalArgumentException("Listener should not be null.");
28         }
29         ListenerRegistrationImpl<T> ret = new ListenerRegistrationImpl<T>(listener);
30         listeners.put(ret,ret);
31         return ret;
32     }
33     
34     @Override
35     public java.util.Iterator<ListenerRegistration<T>> iterator() {
36         return unmodifiableView.iterator();
37     }
38
39     @SuppressWarnings("rawtypes")
40     private void remove(ListenerRegistrationImpl registration) {
41         listeners.remove(registration);
42     }
43
44     private class ListenerRegistrationImpl<P extends EventListener> //
45             extends AbstractObjectRegistration<P> //
46             implements ListenerRegistration<P> {
47
48         public ListenerRegistrationImpl(P instance) {
49             super(instance);
50         }
51
52         @Override
53         protected void removeRegistration() {
54             ListenerRegistry.this.remove(this);
55         }
56     }
57 }