1 package org.shiftone.cache.util; 2 3 4 5 9 public class RingFifo 10 { 11 12 private Object [] array; 13 private int maxSize; 14 private int head; 15 private int size; 16 17 public RingFifo(int maxSize) 18 { 19 20 this.maxSize = maxSize; 21 22 clear(); 23 } 24 25 26 public void clear() 27 { 28 29 array = new Object [maxSize]; 30 head = 0; 31 size = 0; 32 } 33 34 35 public void enqueue(Object obj) 36 { 37 38 array[head] = obj; 39 head = (head + 1) % maxSize; 40 41 if (size < maxSize) 42 { 43 size++; 44 } 45 } 46 47 48 private final int peekIndex() 49 { 50 return (head + maxSize - size) % maxSize; 51 } 52 53 54 public Object peek() 55 { 56 return array[peekIndex()]; 57 } 58 59 60 public Object dequeue() 61 { 62 63 Object obj = null; 64 65 if (size > 0) 66 { 67 int index = peekIndex(); 68 69 obj = array[index]; 70 array[index] = null; 71 72 size--; 73 } 74 75 return obj; 76 } 77 78 79 public int getMaxSize() 80 { 81 return maxSize; 82 } 83 84 85 public int size() 86 { 87 return size; 88 } 89 90 91 public String dump() 92 { 93 94 StringBuffer sb = new StringBuffer (); 95 96 for (int i = 0; i < maxSize; i++) 97 { 98 if (i != 0) 99 { 100 sb.append(","); 101 } 102 103 if (array[i] != null) 104 { 105 sb.append(array[i]); 106 } 107 } 108 109 System.out.println(sb); 110 111 return sb.toString(); 112 } 113 } 114 | Popular Tags |