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
8 package org.opendaylight.yangtools.util.concurrent;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
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;
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
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.
44 * @author Thomas Pantelis
46 * @param <L> the listener type
47 * @param <N> the notification type
49 public final class QueuedNotificationManager<L, N> implements NotificationManager<L, N> {
51 public interface BatchedInvoker<L, N> {
53 * Called to invoke a listener with a notification.
55 * @param listener the listener to invoke
56 * @param notifications notifications to send
58 void invokeListener(@NonNull L listener, @NonNull ImmutableList<N> notifications);
61 private static final Logger LOG = LoggerFactory.getLogger(QueuedNotificationManager.class);
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.
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);
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;
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);
88 * Create a new notification manager.
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
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);
102 * Returns the maximum listener queue capacity.
104 public int getMaxQueueCapacity() {
105 return maxQueueCapacity;
109 * Returns the {@link Executor} to used for notification tasks.
111 public @NonNull Executor getExecutor() {
116 * @see org.opendaylight.yangtools.util.concurrent.NotificationManager#addNotification(L, N)
119 public void submitNotification(final L listener, final N notification) {
120 if (notification != null) {
121 submitNotifications(listener, Collections.singletonList(notification));
126 * @see org.opendaylight.yangtools.util.concurrent.NotificationManager#submitNotifications(L, java.util.Collection)
129 public void submitNotifications(final L listener, final Iterable<N> notifications) {
131 if (notifications == null || listener == null) {
135 LOG.trace("{}: submitNotifications for listener {}: {}", name, listener, notifications);
137 final ListenerKey<L> key = new ListenerKey<>(listener);
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
143 Iterator<N> it = notifications.iterator();
146 NotificationTask task = listenerCache.get(key);
148 // No task found, try to insert a new one
149 final NotificationTask newTask = new NotificationTask(key, it);
150 task = listenerCache.putIfAbsent(key, newTask);
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
155 runTask(listener, newTask);
159 // We have a racing task, hence we can continue, but we need to refresh our iterator from
161 it = newTask.recoverItems();
164 final boolean completed = task.submitNotifications(it);
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);
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);
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.
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);
191 LOG.trace("{}: submitNotifications done for listener {}", name, listener);
195 * Returns {@link ListenerNotificationQueueStats} instances for each current listener
196 * notification task in progress.
198 public List<ListenerNotificationQueueStats> getListenerNotificationQueueStats() {
199 return listenerCache.values().stream().map(t -> new ListenerNotificationQueueStats(t.listenerKey.toString(),
200 t.size())).collect(Collectors.toList());
203 private void runTask(final L listener, final NotificationTask task) {
204 LOG.debug("{}: Submitting NotificationTask for listener {}", name, listener);
205 executor.execute(task);
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
215 private static final class ListenerKey<L> {
216 private final @NonNull L listener;
218 ListenerKey(final L listener) {
219 this.listener = requireNonNull(listener);
222 @NonNull L getListener() {
227 public int hashCode() {
228 return System.identityHashCode(listener);
232 public boolean equals(final Object obj) {
233 return obj == this || obj instanceof ListenerKey<?> && listener == ((ListenerKey<?>) obj).listener;
237 public String toString() {
238 return listener.toString();
243 * Executor task for a single listener that queues notifications and sends them serially to the
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;
253 private final Queue<N> queue = new ArrayDeque<>();
255 private boolean exiting;
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());
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();
279 boolean submitNotifications(final @NonNull Iterator<N> notifications) throws InterruptedException {
280 final long start = System.nanoTime();
281 final long deadline = start + GIVE_UP_NANOS;
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
288 long canWait = deadline - System.nanoTime();
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.
297 final int avail = maxQueueCapacity - queue.size();
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);
307 canWait = notFull.awaitNanos(canWait);
311 for (int i = 0; i < avail; ++i) {
312 if (!notifications.hasNext()) {
317 queue.add(notifications.next());
326 private boolean waitForQueue() {
327 long timeout = TASK_WAIT_NANOS;
329 while (queue.isEmpty()) {
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);
349 // Loop until we've dispatched all the notifications in the queue.
351 final @NonNull ImmutableList<N> notifications;
355 if (!waitForQueue()) {
360 // Splice the entire queue
361 notifications = ImmutableList.copyOf(queue);
369 invokeListener(notifications);
372 // We're exiting, gracefully or not - either way make sure we always remove
373 // ourselves from the cache.
374 listenerCache.remove(listenerKey, this);
378 @SuppressWarnings("checkstyle:illegalCatch")
379 private void invokeListener(final @NonNull ImmutableList<N> notifications) {
380 LOG.debug("{}: Invoking listener {} with notification: {}", name, listenerKey, notifications);
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);