001 package org.apache.jcs.utils.struct;
002
003 /*
004 * Licensed to the Apache Software Foundation (ASF) under one
005 * or more contributor license agreements. See the NOTICE file
006 * distributed with this work for additional information
007 * regarding copyright ownership. The ASF licenses this file
008 * to you under the Apache License, Version 2.0 (the
009 * "License"); you may not use this file except in compliance
010 * with the License. You may obtain a copy of the License at
011 *
012 * http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing,
015 * software distributed under the License is distributed on an
016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017 * KIND, either express or implied. See the License for the
018 * specific language governing permissions and limitations
019 * under the License.
020 */
021
022 /**
023 * This is a bounded queue. It only allows maxSize items.
024 * <p>
025 * @author Aaron Smuts
026 */
027 public class BoundedQueue<T>
028 {
029 /** Queue size limit. */
030 private final int maxSize;
031
032 /** The list backing the queue */
033 private final DoubleLinkedList<DoubleLinkedListNode<T>> list =
034 new DoubleLinkedList<DoubleLinkedListNode<T>>();
035
036 /**
037 * Initialize the bounded queue.
038 * <p>
039 * @param maxSize
040 */
041 public BoundedQueue( int maxSize )
042 {
043 this.maxSize = maxSize;
044 }
045
046 /**
047 * Adds an item to the end of the queue, which is the front of the list.
048 * <p>
049 * @param object
050 */
051 public void add( T object )
052 {
053 if ( list.size() >= maxSize )
054 {
055 list.removeLast();
056 }
057 list.addFirst( new DoubleLinkedListNode<T>( object ) );
058 }
059
060 /**
061 * Takes the last of the underlying double linked list.
062 * <p>
063 * @return null if it is epmpty.
064 */
065 public T take()
066 {
067 DoubleLinkedListNode<T> node = list.removeLast();
068 if ( node != null )
069 {
070 return node.getPayload();
071 }
072 return null;
073 }
074
075 /**
076 * Return the number of items in the queue.
077 * <p>
078 * @return size
079 */
080 public int size()
081 {
082 return list.size();
083 }
084
085 /**
086 * Return true if the size is <= 0;
087 * <p>
088 * @return true is size <= 0;
089 */
090 public boolean isEmpty()
091 {
092 return list.size() <= 0;
093 }
094 }