View Javadoc

1   /*
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   * http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  
20  package org.apache.hadoop.hbase.namequeues.queue;
21  
22  import com.google.common.base.Preconditions;
23  import java.io.Serializable;
24  import java.util.Queue;
25  import java.util.concurrent.ArrayBlockingQueue;
26  import org.apache.hadoop.hbase.classification.InterfaceAudience;
27  
28  @InterfaceAudience.Private
29  public final class EvictingQueue<E> implements Serializable {
30  
31    private final Queue<E> delegate;
32    final int maxSize;
33    private static final long serialVersionUID = 0L;
34  
35    private EvictingQueue(int maxSize) {
36      Preconditions.checkArgument(maxSize >= 0, "maxSize (%s) must >= 0", maxSize);
37      this.delegate = new ArrayBlockingQueue<>(maxSize);
38      this.maxSize = maxSize;
39    }
40  
41    public static <E> EvictingQueue<E> create(int maxSize) {
42      return new EvictingQueue<>(maxSize);
43    }
44  
45    public int remainingCapacity() {
46      return this.maxSize - this.delegate.size();
47    }
48  
49    protected Queue<E> delegate() {
50      return this.delegate;
51    }
52  
53    public boolean offer(E e) {
54      return this.add(e);
55    }
56  
57    public boolean add(E e) {
58      Preconditions.checkNotNull(e);
59      if (this.maxSize == 0) {
60        return true;
61      } else {
62        if (this.delegate().size() == this.maxSize) {
63          this.delegate.remove();
64        }
65        this.delegate.add(e);
66        return true;
67      }
68    }
69  
70    public <T> T[] toArray(T[] array) {
71      return this.delegate().toArray(array);
72    }
73  
74    public void clear() {
75      this.delegate().clear();
76    }
77  
78    public boolean isEmpty() {
79      return this.delegate().isEmpty();
80    }
81  
82    public E poll() {
83      return this.delegate().poll();
84    }
85  }