001/*
002 * (C) Copyright 2006-2009 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Nuxeo - initial API and implementation
016 *
017 * $Id$
018 */
019package org.nuxeo.runtime.management.counters;
020
021import java.util.Iterator;
022import java.util.LinkedList;
023
024/**
025 * Fixed length Stack that is used to store values of a counter over time
026 *
027 * @author Tiry (tdelprat@nuxeo.com)
028 */
029public class CounterHistoryStack implements Iterable<long[]> {
030
031    protected final LinkedList<long[]> list = new LinkedList<long[]>();
032
033    protected final int maxSize;
034
035    public CounterHistoryStack(int size) {
036        maxSize = size;
037    }
038
039    public synchronized void push(long[] item) {
040        list.push(item);
041        if (list.size() > maxSize) {
042            list.remove(list.size() - 1);
043        }
044    }
045
046    @Override
047    public Iterator<long[]> iterator() {
048        return list.iterator();
049    }
050
051    @Override
052    public String toString() {
053        StringBuffer sb = new StringBuffer();
054
055        for (long[] entry : this) {
056            sb.append(entry[0]);
057            sb.append(" => ");
058            sb.append(entry[1]);
059            sb.append("\n");
060        }
061        return sb.toString();
062    }
063
064    public long[] get(int idx) {
065        return list.get(idx);
066    }
067
068    public LinkedList<long[]> getAsList() {
069        return list;
070    }
071}