2 * Copyright (c) 2014 Brocade Communications Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.yangtools.util.concurrent;
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;
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
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.
45 * @author Thomas Pantelis
47 * @param <L> the listener type
48 * @param <N> the notification type
50 public class QueuedNotificationManager<L, N> implements NotificationManager<L, N> {
53 * Interface implemented by clients that does the work of invoking listeners with notifications.
55 * @author Thomas Pantelis
57 * @param <L> the listener type
58 * @param <N> the notification type
60 * @deprecated Use {@link QueuedNotificationManager.BatchedInvoker} instead.
64 public interface Invoker<L, N> {
66 * Called to invoke a listener with a notification.
68 * @param listener the listener to invoke
69 * @param notification the notification to send
71 void invokeListener(L listener, N notification);
75 public interface BatchedInvoker<L, N> {
77 * Called to invoke a listener with a notification.
79 * @param listener the listener to invoke
80 * @param notifications notifications to send
82 void invokeListener(@Nonnull L listener, @Nonnull Collection<? extends N> notifications);
85 private static final Logger LOG = LoggerFactory.getLogger(QueuedNotificationManager.class);
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.
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);
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;
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);
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
118 * @deprecated Use {@link #create(Executor, BatchedInvoker, int, String)} instead.
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 -> {
125 listenerInvoker.invokeListener(l, n);
126 } catch (Exception e) {
127 LOG.error("{}: Error notifying listener {} with {}", name, l, n, e);
130 }), maxQueueCapacity, name);
131 Preconditions.checkNotNull(listenerInvoker);
135 * Create a new notification manager.
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
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);
148 * Returns the maximum listener queue capacity.
150 public int getMaxQueueCapacity() {
151 return maxQueueCapacity;
155 * Returns the {@link Executor} to used for notification tasks.
157 public Executor getExecutor() {
162 * @see org.opendaylight.yangtools.util.concurrent.NotificationManager#addNotification(L, N)
165 public void submitNotification(final L listener, final N notification) throws RejectedExecutionException {
166 if (notification != null) {
167 submitNotifications(listener, Collections.singletonList(notification));
172 * @see org.opendaylight.yangtools.util.concurrent.NotificationManager#submitNotifications(L, java.util.Collection)
175 public void submitNotifications(final L listener, final Iterable<N> notifications)
176 throws RejectedExecutionException {
178 if (notifications == null || listener == null) {
182 LOG.trace("{}: submitNotifications for listener {}: {}", name, listener, notifications);
184 final ListenerKey<L> key = new ListenerKey<>(listener);
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
190 Iterator<N> it = notifications.iterator();
193 NotificationTask task = listenerCache.get(key);
195 // No task found, try to insert a new one
196 final NotificationTask newTask = new NotificationTask(key, it);
197 task = listenerCache.putIfAbsent(key, newTask);
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
202 runTask(listener, newTask);
206 // We have a racing task, hence we can continue, but we need to refresh our iterator from
208 it = newTask.recoverItems();
211 final boolean completed = task.submitNotifications(it);
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);
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);
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.
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);
238 LOG.trace("{}: submitNotifications done for listener {}", name, listener);
242 * Returns {@link ListenerNotificationQueueStats} instances for each current listener
243 * notification task in progress.
245 public List<ListenerNotificationQueueStats> getListenerNotificationQueueStats() {
246 return listenerCache.values().stream().map(t -> new ListenerNotificationQueueStats(t.listenerKey.toString(),
247 t.size())).collect(Collectors.toList());
250 private void runTask(final L listener, final NotificationTask task) {
251 LOG.debug("{}: Submitting NotificationTask for listener {}", name, listener);
252 executor.execute(task);
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
262 private static final class ListenerKey<L> {
263 private final L listener;
265 ListenerKey(final L listener) {
266 this.listener = Preconditions.checkNotNull(listener);
274 public int hashCode() {
275 return System.identityHashCode(listener);
279 public boolean equals(final Object obj) {
283 return (obj instanceof ListenerKey<?>) && listener == ((ListenerKey<?>) obj).listener;
287 public String toString() {
288 return listener.toString();
293 * Executor task for a single listener that queues notifications and sends them serially to the
296 private class NotificationTask implements Runnable {
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;
304 private final Queue<N> queue = new ArrayDeque<>();
306 private boolean exiting;
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());
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();
330 boolean submitNotifications(final Iterator<N> notifications) throws InterruptedException {
331 final long start = System.nanoTime();
332 final long deadline = start + GIVE_UP_NANOS;
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
339 long canWait = deadline - System.nanoTime();
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.
348 final int avail = maxQueueCapacity - queue.size();
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);
358 canWait = notFull.awaitNanos(canWait);
362 for (int i = 0; i < avail; ++i) {
363 if (!notifications.hasNext()) {
368 queue.offer(notifications.next());
377 private boolean waitForQueue() {
378 long timeout = TASK_WAIT_NANOS;
380 while (queue.isEmpty()) {
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);
400 // Loop until we've dispatched all the notifications in the queue.
402 final Collection<N> notifications;
406 if (!waitForQueue()) {
411 // Splice the entire queue
412 notifications = ImmutableList.copyOf(queue);
420 invokeListener(notifications);
423 // We're exiting, gracefully or not - either way make sure we always remove
424 // ourselves from the cache.
425 listenerCache.remove(listenerKey, this);
429 private void invokeListener(final Collection<N> notifications) {
430 LOG.debug("{}: Invoking listener {} with notification: {}", name, listenerKey, notifications);
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);