01: package org.shiftone.cache.util;
02:
03: /**
04: * @author <a href="mailto:jeff@shiftone.org">Jeff Drost</a>
05: * @version $Revision: 1.2 $
06: */
07: public class RingFifo {
08:
09: private Object[] array;
10: private int maxSize;
11: private int head;
12: private int size;
13:
14: public RingFifo(int maxSize) {
15:
16: this .maxSize = maxSize;
17:
18: clear();
19: }
20:
21: public void clear() {
22:
23: array = new Object[maxSize];
24: head = 0;
25: size = 0;
26: }
27:
28: public void enqueue(Object obj) {
29:
30: array[head] = obj;
31: head = (head + 1) % maxSize;
32:
33: if (size < maxSize) {
34: size++;
35: }
36: }
37:
38: private final int peekIndex() {
39: return (head + maxSize - size) % maxSize;
40: }
41:
42: public Object peek() {
43: return array[peekIndex()];
44: }
45:
46: public Object dequeue() {
47:
48: Object obj = null;
49:
50: if (size > 0) {
51: int index = peekIndex();
52:
53: obj = array[index];
54: array[index] = null;
55:
56: size--;
57: }
58:
59: return obj;
60: }
61:
62: public int getMaxSize() {
63: return maxSize;
64: }
65:
66: public int size() {
67: return size;
68: }
69:
70: public String dump() {
71:
72: StringBuffer sb = new StringBuffer();
73:
74: for (int i = 0; i < maxSize; i++) {
75: if (i != 0) {
76: sb.append(",");
77: }
78:
79: if (array[i] != null) {
80: sb.append(array[i]);
81: }
82: }
83:
84: System.out.println(sb);
85:
86: return sb.toString();
87: }
88: }
|