2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 package org.apache.log4j.helpers;
20 import org.apache.log4j.spi.LoggingEvent;
24 CyclicBuffer is used by other appenders to hold {@link LoggingEvent
25 LoggingEvents} for immediate or differed display.
27 <p>This buffer gives read access to any element in the buffer not
28 just the first or last element.
30 @author Ceki Gülcü
34 public class CyclicBuffer {
43 Instantiate a new CyclicBuffer of at most <code>maxSize</code> events.
45 The <code>maxSize</code> argument must a positive integer.
47 @param maxSize The maximum number of elements in the buffer.
49 public CyclicBuffer(int maxSize) throws IllegalArgumentException {
51 throw new IllegalArgumentException("The maxSize argument ("+maxSize+
52 ") is not a positive integer.");
54 this.maxSize = maxSize;
55 ea = new LoggingEvent[maxSize];
62 Add an <code>event</code> as the last event in the buffer.
66 void add(LoggingEvent event) {
68 if(++last == maxSize) {
72 if(numElems < maxSize) {
74 } else if(++first == maxSize) {
81 Get the <i>i</i>th oldest event currently in the buffer. If
82 <em>i</em> is outside the range 0 to the number of elements
83 currently in the buffer, then <code>null</code> is returned.
88 LoggingEvent get(int i) {
89 if(i < 0 || i >= numElems) {
93 return ea[(first + i) % maxSize];
102 Get the oldest (first) element in the buffer. The oldest element
103 is removed from the buffer.
107 LoggingEvent r = null;
112 if(++first == maxSize) {
120 Get the number of elements in the buffer. This number is
121 guaranteed to be in the range 0 to <code>maxSize</code>
130 Resize the cyclic buffer to <code>newSize</code>.
132 @throws IllegalArgumentException if <code>newSize</code> is negative.
135 void resize(int newSize) {
137 throw new IllegalArgumentException("Negative array size ["+newSize+
140 if(newSize == numElems)
142 return; // nothing to do
145 LoggingEvent[] temp = new LoggingEvent[newSize];
147 int loopLen = newSize < numElems ? newSize : numElems;
149 for(int i = 0; i < loopLen; i++) {
152 if(++first == numElems) {
160 if (loopLen == newSize) {