Improve notification delivery defensiveness
[mdsal.git] / dom / mdsal-dom-broker / src / main / java / org / opendaylight / mdsal / dom / broker / DOMNotificationRouterEvent.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.mdsal.dom.broker;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.util.concurrent.ListenableFuture;
13 import com.google.common.util.concurrent.SettableFuture;
14 import com.lmax.disruptor.EventFactory;
15 import java.util.Collection;
16 import org.opendaylight.mdsal.dom.api.DOMNotification;
17 import org.opendaylight.mdsal.dom.api.DOMNotificationListener;
18 import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21
22 /**
23  * A single notification event in the disruptor ringbuffer. These objects are reused, so they do have mutable state.
24  */
25 final class DOMNotificationRouterEvent {
26     private static final Logger LOG = LoggerFactory.getLogger(DOMNotificationRouterEvent.class);
27
28     static final EventFactory<DOMNotificationRouterEvent> FACTORY = DOMNotificationRouterEvent::new;
29
30     private Collection<AbstractListenerRegistration<? extends DOMNotificationListener>> subscribers;
31     private DOMNotification notification;
32     private SettableFuture<Void> future;
33
34     private DOMNotificationRouterEvent() {
35         // Hidden on purpose, initialized in initialize()
36     }
37
38     @SuppressWarnings("checkstyle:hiddenField")
39     ListenableFuture<Void> initialize(final DOMNotification notification,
40             final Collection<AbstractListenerRegistration<? extends DOMNotificationListener>> subscribers) {
41         this.notification = requireNonNull(notification);
42         this.subscribers = requireNonNull(subscribers);
43         this.future = SettableFuture.create();
44         return this.future;
45     }
46
47     @SuppressWarnings("checkstyle:illegalCatch")
48     void deliverNotification() {
49         for (AbstractListenerRegistration<? extends DOMNotificationListener> reg : subscribers) {
50             if (reg.notClosed()) {
51                 final DOMNotificationListener listener = reg.getInstance();
52                 try {
53                     listener.onNotification(notification);
54                 } catch (Exception e) {
55                     LOG.warn("Listener {} failed during notification delivery", listener, e);
56                 }
57             }
58         }
59     }
60
61     void setFuture() {
62         future.set(null);
63     }
64 }