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