001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.activemq.memory.buffer;
018    
019    import java.util.Iterator;
020    import java.util.LinkedList;
021    
022    /**
023     * A {@link MessageBuffer} which evicts messages in arrival order so the oldest
024     * messages are removed first.
025     * 
026     * 
027     */
028    public class OrderBasedMessageBuffer implements MessageBuffer {
029    
030        private int limit = 100 * 64 * 1024;
031        private LinkedList<MessageQueue> list = new LinkedList<MessageQueue>();
032        private int size;
033        private Object lock = new Object();
034    
035        public OrderBasedMessageBuffer() {
036        }
037    
038        public OrderBasedMessageBuffer(int limit) {
039            this.limit = limit;
040        }
041    
042        public int getSize() {
043            synchronized (lock) {
044                return size;
045            }
046        }
047    
048        /**
049         * Creates a new message queue instance
050         */
051        public MessageQueue createMessageQueue() {
052            return new MessageQueue(this);
053        }
054    
055        /**
056         * After a message queue has changed we may need to perform some evictions
057         * 
058         * @param delta
059         * @param queueSize
060         */
061        public void onSizeChanged(MessageQueue queue, int delta, int queueSize) {
062            synchronized (lock) {
063                list.addLast(queue);
064                size += delta;
065                while (size > limit) {
066                    MessageQueue biggest = list.removeFirst();
067                    size -= biggest.evictMessage();
068                }
069            }
070        }
071    
072        public void clear() {
073            synchronized (lock) {
074                for (Iterator<MessageQueue> iter = list.iterator(); iter.hasNext();) {
075                    MessageQueue queue = iter.next();
076                    queue.clear();
077                }
078                size = 0;
079            }
080        }
081    
082    }