KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > activemq > memory > buffer > OrderBasedMessageBuffer


1 /**
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one or more
4  * contributor license agreements. See the NOTICE file distributed with
5  * this work for additional information regarding copyright ownership.
6  * The ASF licenses this file to You under the Apache License, Version 2.0
7  * (the "License"); you may not use this file except in compliance with
8  * 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.activemq.memory.buffer;
19
20 import java.util.Iterator JavaDoc;
21 import java.util.LinkedList JavaDoc;
22
23 /**
24  * A {@link MessageBuffer} which evicts messages in arrival order so the oldest
25  * messages are removed first.
26  *
27  * @version $Revision: 1.1 $
28  */

29 public class OrderBasedMessageBuffer implements MessageBuffer {
30
31     private int limit = 100 * 64 * 1024;
32     private LinkedList JavaDoc list = new LinkedList JavaDoc();
33     private int size;
34     private Object JavaDoc lock = new Object JavaDoc();
35
36     public OrderBasedMessageBuffer() {
37     }
38
39     public OrderBasedMessageBuffer(int limit) {
40         this.limit = limit;
41     }
42
43     public int getSize() {
44         synchronized (lock) {
45             return size;
46         }
47     }
48
49     /**
50      * Creates a new message queue instance
51      */

52     public MessageQueue createMessageQueue() {
53         return new MessageQueue(this);
54     }
55
56     /**
57      * After a message queue has changed we may need to perform some evictions
58      *
59      * @param delta
60      * @param queueSize
61      */

62     public void onSizeChanged(MessageQueue queue, int delta, int queueSize) {
63         synchronized (lock) {
64             list.addLast(queue);
65             size += delta;
66             while (size > limit) {
67                 MessageQueue biggest = (MessageQueue) list.removeFirst();
68                 size -= biggest.evictMessage();
69             }
70         }
71     }
72
73     public void clear() {
74         synchronized (lock) {
75             for (Iterator JavaDoc iter = list.iterator(); iter.hasNext();) {
76                 MessageQueue queue = (MessageQueue) iter.next();
77                 queue.clear();
78             }
79             size = 0;
80         }
81     }
82
83 }
84
Popular Tags