01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.stats;
05:
06: import java.util.LinkedList;
07:
08: /**
09: * A stack with a fixed depth (pushing beyond the depth of the stack will discard oldest item)
10: */
11: public class LossyStack {
12:
13: private final LinkedList data = new LinkedList();
14: private final int maxDepth;
15:
16: public LossyStack(int depth) {
17: if (depth < 1) {
18: throw new IllegalArgumentException(
19: "stack depth must be greater than or equal to 1");
20: }
21: this .maxDepth = depth;
22: }
23:
24: public synchronized void push(Object obj) {
25: // we could slightly optimize the mostRecent() call by specifically storing the reference
26: // to the last object added in a dedicated variable
27: data.addFirst(obj);
28: if (data.size() > maxDepth) {
29: data.removeLast();
30: }
31: }
32:
33: public synchronized Object pop() {
34: if (data.isEmpty()) {
35: throw new IllegalStateException("stack empty");
36: }
37: return data.removeFirst();
38: }
39:
40: public synchronized Object[] toArray(Object[] type) {
41: return data.toArray(type);
42: }
43:
44: public synchronized Object peek() {
45: if (data.isEmpty()) {
46: return null;
47: }
48: return data.getFirst();
49: }
50:
51: public synchronized boolean isEmtpy() {
52: return data.isEmpty();
53: }
54:
55: public synchronized int depth() {
56: return data.size();
57: }
58:
59: }
|