5160efe9bf7ccd785a9455335973605906999f61
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / concurrent / QueuedNotificationManager.java
1 /*
2  * Copyright (c) 2014 Brocade Communications 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
9 package org.opendaylight.yangtools.util.concurrent;
10
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableList;
13 import java.util.ArrayDeque;
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.Iterator;
17 import java.util.List;
18 import java.util.Queue;
19 import java.util.concurrent.ConcurrentHashMap;
20 import java.util.concurrent.ConcurrentMap;
21 import java.util.concurrent.Executor;
22 import java.util.concurrent.RejectedExecutionException;
23 import java.util.concurrent.TimeUnit;
24 import java.util.concurrent.locks.Condition;
25 import java.util.concurrent.locks.Lock;
26 import java.util.concurrent.locks.ReentrantLock;
27 import java.util.stream.Collectors;
28 import javax.annotation.Nonnull;
29 import javax.annotation.concurrent.GuardedBy;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 /**
34  * This class manages queuing and dispatching notifications for multiple listeners concurrently.
35  * Notifications are queued on a per-listener basis and dispatched serially to each listener via an
36  * {@link Executor}.
37  *
38  * <p>This class optimizes its memory footprint by only allocating and maintaining a queue and executor
39  * task for a listener when there are pending notifications. On the first notification(s), a queue
40  * is created and a task is submitted to the executor to dispatch the queue to the associated
41  * listener. Any subsequent notifications that occur before all previous notifications have been
42  * dispatched are appended to the existing queue. When all notifications have been dispatched, the
43  * queue and task are discarded.
44  *
45  * @author Thomas Pantelis
46  *
47  * @param <L> the listener type
48  * @param <N> the notification type
49  */
50 public class QueuedNotificationManager<L, N> implements NotificationManager<L, N> {
51
52     /**
53      * Interface implemented by clients that does the work of invoking listeners with notifications.
54      *
55      * @author Thomas Pantelis
56      *
57      * @param <L> the listener type
58      * @param <N> the notification type
59      *
60      * @deprecated Use {@link QueuedNotificationManager.BatchedInvoker} instead.
61      */
62     @Deprecated
63     @FunctionalInterface
64     public interface Invoker<L, N> {
65         /**
66          * Called to invoke a listener with a notification.
67          *
68          * @param listener the listener to invoke
69          * @param notification the notification to send
70          */
71         void invokeListener(L listener, N notification);
72     }
73
74     @FunctionalInterface
75     public interface BatchedInvoker<L, N> {
76         /**
77          * Called to invoke a listener with a notification.
78          *
79          * @param listener the listener to invoke
80          * @param notifications notifications to send
81          */
82         void invokeListener(@Nonnull L listener, @Nonnull Collection<? extends N> notifications);
83     }
84
85     private static final Logger LOG = LoggerFactory.getLogger(QueuedNotificationManager.class);
86
87     /**
88      * Caps the maximum number of attempts to offer notification to a particular listener.  Each
89      * attempt window is 1 minute, so an offer times out after roughly 10 minutes.
90      */
91     private static final int MAX_NOTIFICATION_OFFER_MINUTES = 10;
92     private static final long GIVE_UP_NANOS = TimeUnit.MINUTES.toNanos(MAX_NOTIFICATION_OFFER_MINUTES);
93     private static final long TASK_WAIT_NANOS = TimeUnit.MILLISECONDS.toNanos(10);
94
95     private final ConcurrentMap<ListenerKey<L>, NotificationTask> listenerCache = new ConcurrentHashMap<>();
96     private final BatchedInvoker<L, N> listenerInvoker;
97     private final Executor executor;
98     private final String name;
99     private final int maxQueueCapacity;
100
101     private QueuedNotificationManager(final Executor executor, final BatchedInvoker<L, N> listenerInvoker,
102             final int maxQueueCapacity, final String name) {
103         Preconditions.checkArgument(maxQueueCapacity > 0, "Invalid maxQueueCapacity %s must be > 0", maxQueueCapacity);
104         this.executor = Preconditions.checkNotNull(executor);
105         this.listenerInvoker = Preconditions.checkNotNull(listenerInvoker);
106         this.maxQueueCapacity = maxQueueCapacity;
107         this.name = Preconditions.checkNotNull(name);
108     }
109
110     /**
111      * Constructor.
112      *
113      * @param executor the {@link Executor} to use for notification tasks
114      * @param listenerInvoker the {@link Invoker} to use for invoking listeners
115      * @param maxQueueCapacity the capacity of each listener queue
116      * @param name the name of this instance for logging info
117      *
118      * @deprecated Use {@link #create(Executor, BatchedInvoker, int, String)} instead.
119      */
120     @Deprecated
121     public QueuedNotificationManager(final Executor executor, final Invoker<L, N> listenerInvoker,
122             final int maxQueueCapacity, final String name) {
123         this(executor, (BatchedInvoker<L, N>)(l, c) -> c.forEach(n -> {
124             try {
125                 listenerInvoker.invokeListener(l, n);
126             } catch (Exception e) {
127                 LOG.error("{}: Error notifying listener {} with {}", name, l, n, e);
128             }
129
130         }), maxQueueCapacity, name);
131         Preconditions.checkNotNull(listenerInvoker);
132     }
133
134     /**
135      * Create a new notification manager.
136      *
137      * @param executor the {@link Executor} to use for notification tasks
138      * @param listenerInvoker the {@link BatchedInvoker} to use for invoking listeners
139      * @param maxQueueCapacity the capacity of each listener queue
140      * @param name the name of this instance for logging info
141      */
142     public static <L, N> QueuedNotificationManager<L, N> create(final Executor executor,
143             final BatchedInvoker<L, N> listenerInvoker, final int maxQueueCapacity, final String name) {
144         return new QueuedNotificationManager<>(executor, listenerInvoker, maxQueueCapacity, name);
145     }
146
147     /**
148      * Returns the maximum listener queue capacity.
149      */
150     public int getMaxQueueCapacity() {
151         return maxQueueCapacity;
152     }
153
154     /**
155      * Returns the {@link Executor} to used for notification tasks.
156      */
157     public Executor getExecutor() {
158         return executor;
159     }
160
161     /* (non-Javadoc)
162      * @see org.opendaylight.yangtools.util.concurrent.NotificationManager#addNotification(L, N)
163      */
164     @Override
165     public void submitNotification(final L listener, final N notification) throws RejectedExecutionException {
166         if (notification != null) {
167             submitNotifications(listener, Collections.singletonList(notification));
168         }
169     }
170
171     /* (non-Javadoc)
172      * @see org.opendaylight.yangtools.util.concurrent.NotificationManager#submitNotifications(L, java.util.Collection)
173      */
174     @Override
175     public void submitNotifications(final L listener, final Iterable<N> notifications)
176             throws RejectedExecutionException {
177
178         if (notifications == null || listener == null) {
179             return;
180         }
181
182         LOG.trace("{}: submitNotifications for listener {}: {}", name, listener, notifications);
183
184         final ListenerKey<L> key = new ListenerKey<>(listener);
185
186         // Keep looping until we are either able to add a new NotificationTask or are able to
187         // add our notifications to an existing NotificationTask. Eventually one or the other
188         // will occur.
189         try {
190             Iterator<N> it = notifications.iterator();
191
192             while (true) {
193                 NotificationTask task = listenerCache.get(key);
194                 if (task == null) {
195                     // No task found, try to insert a new one
196                     final NotificationTask newTask = new NotificationTask(key, it);
197                     task = listenerCache.putIfAbsent(key, newTask);
198                     if (task == null) {
199                         // We were able to put our new task - now submit it to the executor and
200                         // we're done. If it throws a RejectedExecutionException, let that propagate
201                         // to the caller.
202                         runTask(listener, newTask);
203                         break;
204                     }
205
206                     // We have a racing task, hence we can continue, but we need to refresh our iterator from
207                     // the task.
208                     it = newTask.recoverItems();
209                 }
210
211                 final boolean completed = task.submitNotifications(it);
212                 if (!completed) {
213                     // Task is indicating it is exiting before it has consumed all the items and is exiting. Rather
214                     // than spinning on removal, we try to replace it.
215                     final NotificationTask newTask = new NotificationTask(key, it);
216                     if (listenerCache.replace(key, task, newTask)) {
217                         runTask(listener, newTask);
218                         break;
219                     }
220
221                     // We failed to replace the task, hence we need retry. Note we have to recover the items to be
222                     // published from the new task.
223                     it = newTask.recoverItems();
224                     LOG.debug("{}: retrying task queueing for {}", name, listener);
225                     continue;
226                 }
227
228                 // All notifications have either been delivered or we have timed out and warned about the ones we
229                 // have failed to deliver. In any case we are done here.
230                 break;
231             }
232         } catch (InterruptedException e) {
233             // We were interrupted trying to offer to the listener's queue. Somebody's probably
234             // telling us to quit.
235             LOG.warn("{}: Interrupted trying to add to {} listener's queue", name, listener);
236         }
237
238         LOG.trace("{}: submitNotifications done for listener {}", name, listener);
239     }
240
241     /**
242      * Returns {@link ListenerNotificationQueueStats} instances for each current listener
243      * notification task in progress.
244      */
245     public List<ListenerNotificationQueueStats> getListenerNotificationQueueStats() {
246         return listenerCache.values().stream().map(t -> new ListenerNotificationQueueStats(t.listenerKey.toString(),
247             t.size())).collect(Collectors.toList());
248     }
249
250     private void runTask(final L listener, final NotificationTask task) {
251         LOG.debug("{}: Submitting NotificationTask for listener {}", name, listener);
252         executor.execute(task);
253     }
254
255     /**
256      * Used as the listenerCache map key. We key by listener reference identity hashCode/equals.
257      * Since we don't know anything about the listener class implementations and we're mixing
258      * multiple listener class instances in the same map, this avoids any potential issue with an
259      * equals implementation that just blindly casts the other Object to compare instead of checking
260      * for instanceof.
261      */
262     private static final class ListenerKey<L> {
263         private final L listener;
264
265         ListenerKey(final L listener) {
266             this.listener = Preconditions.checkNotNull(listener);
267         }
268
269         L getListener() {
270             return listener;
271         }
272
273         @Override
274         public int hashCode() {
275             return System.identityHashCode(listener);
276         }
277
278         @Override
279         public boolean equals(final Object obj) {
280             if (obj == this) {
281                 return true;
282             }
283             return (obj instanceof ListenerKey<?>) && listener == ((ListenerKey<?>) obj).listener;
284         }
285
286         @Override
287         public String toString() {
288             return listener.toString();
289         }
290     }
291
292     /**
293      * Executor task for a single listener that queues notifications and sends them serially to the
294      * listener.
295      */
296     private class NotificationTask implements Runnable {
297
298         private final Lock lock = new ReentrantLock();
299         private final Condition notEmpty = lock.newCondition();
300         private final Condition notFull = lock.newCondition();
301         private final ListenerKey<L> listenerKey;
302
303         @GuardedBy("lock")
304         private final Queue<N> queue = new ArrayDeque<>();
305         @GuardedBy("lock")
306         private boolean exiting;
307
308         NotificationTask(final ListenerKey<L> listenerKey, final Iterator<N> notifications) {
309             this.listenerKey = Preconditions.checkNotNull(listenerKey);
310             while (notifications.hasNext()) {
311                 queue.offer(notifications.next());
312             }
313         }
314
315         Iterator<N> recoverItems() {
316             // This violates @GuardedBy annotation, but is invoked only when the task is not started and will never
317             // get started, hence this is safe.
318             return queue.iterator();
319         }
320
321         int size() {
322             lock.lock();
323             try {
324                 return queue.size();
325             } finally {
326                 lock.unlock();
327             }
328         }
329
330         boolean submitNotifications(final Iterator<N> notifications) throws InterruptedException {
331             final long start = System.nanoTime();
332             final long deadline = start + GIVE_UP_NANOS;
333
334             lock.lock();
335             try {
336                 // Lock may have blocked for some time, we need to take that into account. We may have exceedded
337                 // the deadline, but that is unlikely and even in that case we can make some progress without further
338                 // blocking.
339                 long canWait = deadline - System.nanoTime();
340
341                 while (true) {
342                     // Check the exiting flag - if true then #run is in the process of exiting so return
343                     // false to indicate such. Otherwise, offer the notifications to the queue.
344                     if (exiting) {
345                         return false;
346                     }
347
348                     final int avail = maxQueueCapacity - queue.size();
349                     if (avail <= 0) {
350                         if (canWait <= 0) {
351                             LOG.warn("{}: Failed to offer notifications {} to the queue for listener {}. Exceeded"
352                                 + "maximum allowable time of {} minutes; the listener is likely in an unrecoverable"
353                                 + "state (deadlock or endless loop). ", name, ImmutableList.copyOf(notifications),
354                                 listenerKey, MAX_NOTIFICATION_OFFER_MINUTES);
355                             return true;
356                         }
357
358                         canWait = notFull.awaitNanos(canWait);
359                         continue;
360                     }
361
362                     for (int i = 0; i < avail; ++i) {
363                         if (!notifications.hasNext()) {
364                             notEmpty.signal();
365                             return true;
366                         }
367
368                         queue.offer(notifications.next());
369                     }
370                 }
371             } finally {
372                 lock.unlock();
373             }
374         }
375
376         @GuardedBy("lock")
377         private boolean waitForQueue() {
378             long timeout = TASK_WAIT_NANOS;
379
380             while (queue.isEmpty()) {
381                 if (timeout <= 0) {
382                     return false;
383                 }
384
385                 try {
386                     timeout = notEmpty.awaitNanos(timeout);
387                 } catch (InterruptedException e) {
388                     // The executor is probably shutting down so log as debug.
389                     LOG.debug("{}: Interrupted trying to remove from {} listener's queue", name, listenerKey);
390                     return false;
391                 }
392             }
393
394             return true;
395         }
396
397         @Override
398         public void run() {
399             try {
400                 // Loop until we've dispatched all the notifications in the queue.
401                 while (true) {
402                     final Collection<N> notifications;
403
404                     lock.lock();
405                     try {
406                         if (!waitForQueue()) {
407                             exiting = true;
408                             break;
409                         }
410
411                         // Splice the entire queue
412                         notifications = ImmutableList.copyOf(queue);
413                         queue.clear();
414
415                         notFull.signalAll();
416                     } finally {
417                         lock.unlock();
418                     }
419
420                     invokeListener(notifications);
421                 }
422             } finally {
423                 // We're exiting, gracefully or not - either way make sure we always remove
424                 // ourselves from the cache.
425                 listenerCache.remove(listenerKey, this);
426             }
427         }
428
429         private void invokeListener(final Collection<N> notifications) {
430             LOG.debug("{}: Invoking listener {} with notification: {}", name, listenerKey, notifications);
431             try {
432                 listenerInvoker.invokeListener(listenerKey.getListener(), notifications);
433             } catch (Exception e) {
434                 // We'll let a RuntimeException from the listener slide and keep sending any remaining notifications.
435                 LOG.error("{}: Error notifying listener {} with {}", name, listenerKey, notifications, e);
436             }
437         }
438     }
439 }