View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.util;
19  
20  import java.util.AbstractQueue;
21  import java.util.Iterator;
22  
23  import org.apache.hadoop.hbase.classification.InterfaceAudience;
24  
25  /**
26   * A bounded non-thread safe implementation of {@link java.util.Queue}.
27   */
28  @InterfaceAudience.Private
29  public class BoundedArrayQueue<E> extends AbstractQueue<E> {
30  
31    private Object[] items;
32    private int takeIndex, putIndex;
33    private int count;
34  
35    public BoundedArrayQueue(int maxElements) {
36      items =  new Object[maxElements];
37    }
38  
39    @Override
40    public int size() {
41      return count;
42    }
43  
44    /**
45     * Not implemented and will throw {@link UnsupportedOperationException}
46     */
47    @Override
48    public Iterator<E> iterator() {
49      // We don't need this. Leaving it as not implemented.
50      throw new UnsupportedOperationException();
51    }
52  
53    @Override
54    public boolean offer(E e) {
55      if (count == items.length) return false;
56      items[putIndex] = e;
57      if (++putIndex == items.length) putIndex = 0;
58      count++;
59      return true;
60    }
61  
62    @Override
63    public E poll() {
64      return (count == 0) ? null : dequeue();
65    }
66  
67    @SuppressWarnings("unchecked")
68    private E dequeue() {
69      E x = (E) items[takeIndex];
70      items[takeIndex] = null;
71      if (++takeIndex == items.length) takeIndex = 0;
72      count--;
73      return x;
74    }
75  
76    @SuppressWarnings("unchecked")
77    @Override
78    public E peek() {
79      return (E) items[takeIndex];
80    }
81  }