85265e8fd467b6221bdd6df599f1eec3c1ebb64d
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / sal / binding / impl / GenerationalListenerMap.java
1 /**
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.sal.binding.impl;
9
10 import java.util.concurrent.atomic.AtomicReference;
11
12 import javax.annotation.concurrent.GuardedBy;
13
14 import org.opendaylight.yangtools.yang.binding.Notification;
15
16 import com.google.common.collect.HashMultimap;
17 import com.google.common.collect.Multimap;
18
19 /**
20  * A multi-generation, isolated notification type to listener map.
21  */
22 final class GenerationalListenerMap {
23     private final AtomicReference<ListenerMapGeneration> current = new AtomicReference<>(new ListenerMapGeneration());
24
25     Iterable<NotificationListenerRegistration<?>> listenersFor(final Notification notification) {
26         return current.get().listenersFor(notification);
27     }
28
29     Iterable<Class<? extends Notification>> getKnownTypes() {
30         // Note: this relies on current having immutable listeners
31         return current.get().getListeners().keySet();
32     }
33
34     @GuardedBy("this")
35     private Multimap<Class<? extends Notification>, NotificationListenerRegistration<?>> mutableListeners() {
36         return HashMultimap.create(current.get().getListeners());
37     }
38
39     synchronized void addRegistrations(final NotificationListenerRegistration<?>... registrations) {
40         Multimap<Class<? extends Notification>, NotificationListenerRegistration<?>> listeners =
41                 mutableListeners();
42
43         for (NotificationListenerRegistration<?> reg : registrations) {
44             listeners.put(reg.getType(), reg);
45         }
46
47         current.set(new ListenerMapGeneration(listeners));
48     }
49
50     synchronized void removeRegistrations(final NotificationListenerRegistration<?>... registrations) {
51         Multimap<Class<? extends Notification>, NotificationListenerRegistration<?>> listeners =
52                 mutableListeners();
53
54         for (NotificationListenerRegistration<?> reg : registrations) {
55             listeners.remove(reg.getType(), reg);
56         }
57
58         current.set(new ListenerMapGeneration(listeners));
59     }
60 }