1 16 17 package org.apache.log4j.helpers; 18 19 import org.apache.log4j.spi.LoggingEvent; 20 21 33 public class CyclicBuffer { 34 35 LoggingEvent[] ea; 36 int first; 37 int last; 38 int numElems; 39 int maxSize; 40 41 48 public CyclicBuffer(int maxSize) throws IllegalArgumentException { 49 if(maxSize < 1) { 50 throw new IllegalArgumentException ("The maxSize argument ("+maxSize+ 51 ") is not a positive integer."); 52 } 53 this.maxSize = maxSize; 54 ea = new LoggingEvent[maxSize]; 55 first = 0; 56 last = 0; 57 numElems = 0; 58 } 59 60 64 public 65 void add(LoggingEvent event) { 66 ea[last] = event; 67 if(++last == maxSize) 68 last = 0; 69 70 if(numElems < maxSize) 71 numElems++; 72 else if(++first == maxSize) 73 first = 0; 74 } 75 76 77 84 public 85 LoggingEvent get(int i) { 86 if(i < 0 || i >= numElems) 87 return null; 88 89 return ea[(first + i) % maxSize]; 90 } 91 92 public 93 int getMaxSize() { 94 return maxSize; 95 } 96 97 101 public 102 LoggingEvent get() { 103 LoggingEvent r = null; 104 if(numElems > 0) { 105 numElems--; 106 r = ea[first]; 107 ea[first] = null; 108 if(++first == maxSize) 109 first = 0; 110 } 111 return r; 112 } 113 114 119 public 120 int length() { 121 return numElems; 122 } 123 124 129 public 130 void resize(int newSize) { 131 if(newSize < 0) { 132 throw new IllegalArgumentException ("Negative array size ["+newSize+ 133 "] not allowed."); 134 } 135 if(newSize == numElems) 136 return; 138 LoggingEvent[] temp = new LoggingEvent[newSize]; 139 140 int loopLen = newSize < numElems ? newSize : numElems; 141 142 for(int i = 0; i < loopLen; i++) { 143 temp[i] = ea[first]; 144 ea[first] = null; 145 if(++first == numElems) 146 first = 0; 147 } 148 ea = temp; 149 first = 0; 150 numElems = loopLen; 151 maxSize = newSize; 152 if (loopLen == newSize) { 153 last = 0; 154 } else { 155 last = loopLen; 156 } 157 } 158 } 159 | Popular Tags |