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 com.google.common.annotations.Beta;
11 import java.lang.invoke.MethodHandles;
12 import java.lang.invoke.VarHandle;
13 import java.util.Collection;
14 import java.util.concurrent.LinkedBlockingQueue;
15 import java.util.concurrent.TimeUnit;
16 import org.eclipse.jdt.annotation.NonNull;
19 * A {@link LinkedBlockingQueue} that tracks the largest queue size for debugging.
21 * @author Thomas Pantelis
23 * @param <E> the element t.ype
25 public class TrackingLinkedBlockingQueue<E> extends LinkedBlockingQueue<E> {
27 private static final long serialVersionUID = 1L;
29 private static final VarHandle LARGEST_QUEUE_SIZE;
33 LARGEST_QUEUE_SIZE = MethodHandles.lookup()
34 .findVarHandle(TrackingLinkedBlockingQueue.class, "largestQueueSize", int.class);
35 } catch (NoSuchFieldException | IllegalAccessException e) {
36 throw new ExceptionInInitializerError(e);
41 * Holds largestQueueSize, this field should be only updated using {@link #LARGEST_QUEUE_SIZE}.
43 private volatile int largestQueueSize;
46 * See {@link LinkedBlockingQueue#LinkedBlockingQueue()}.
48 public TrackingLinkedBlockingQueue() {
52 * See {@link LinkedBlockingQueue#LinkedBlockingQueue(Collection)}.
54 @SuppressWarnings("checkstyle:parameterName")
55 public TrackingLinkedBlockingQueue(final @NonNull Collection<? extends E> c) {
60 * See {@link LinkedBlockingQueue#LinkedBlockingQueue(int)}.
62 public TrackingLinkedBlockingQueue(final int capacity) {
67 * Returns the largest queue size.
70 // FIXME: 11.0.0: return int
71 public long getLargestQueueSize() {
72 return largestQueueSize;
76 @SuppressWarnings("checkstyle:parameterName")
77 public boolean offer(final E e, final long timeout, final TimeUnit unit) throws InterruptedException {
78 if (super.offer(e, timeout, unit)) {
79 updateLargestQueueSize();
87 @SuppressWarnings("checkstyle:parameterName")
88 public boolean offer(final E e) {
90 updateLargestQueueSize();
98 @SuppressWarnings("checkstyle:parameterName")
99 public void put(final E e) throws InterruptedException {
101 updateLargestQueueSize();
105 @SuppressWarnings("checkstyle:parameterName")
106 public boolean add(final E e) {
107 boolean result = super.add(e);
108 updateLargestQueueSize();
113 @SuppressWarnings("checkstyle:parameterName")
114 public boolean addAll(final Collection<? extends E> c) {
116 return super.addAll(c);
118 updateLargestQueueSize();
122 private void updateLargestQueueSize() {
123 final int size = size();
125 int largest = (int) LARGEST_QUEUE_SIZE.getAcquire(this);
126 while (largest < size) {
127 largest = (int) LARGEST_QUEUE_SIZE.compareAndExchangeRelease(this, largest, size);