001/*
002 * (C) Copyright 2006-2009 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 *
019 * $Id$
020 */
021package org.nuxeo.runtime.management.counters;
022
023import java.util.Iterator;
024import java.util.LinkedList;
025
026/**
027 * Fixed length Stack that is used to store values of a counter over time
028 *
029 * @author Tiry (tdelprat@nuxeo.com)
030 */
031public class CounterHistoryStack implements Iterable<long[]> {
032
033    protected final LinkedList<long[]> list = new LinkedList<long[]>();
034
035    protected final int maxSize;
036
037    public CounterHistoryStack(int size) {
038        maxSize = size;
039    }
040
041    public synchronized void push(long[] item) {
042        list.push(item);
043        if (list.size() > maxSize) {
044            list.remove(list.size() - 1);
045        }
046    }
047
048    @Override
049    public Iterator<long[]> iterator() {
050        return list.iterator();
051    }
052
053    @Override
054    public String toString() {
055        StringBuffer sb = new StringBuffer();
056
057        for (long[] entry : this) {
058            sb.append(entry[0]);
059            sb.append(" => ");
060            sb.append(entry[1]);
061            sb.append("\n");
062        }
063        return sb.toString();
064    }
065
066    public long[] get(int idx) {
067        return list.get(idx);
068    }
069
070    public LinkedList<long[]> getAsList() {
071        return list;
072    }
073}