KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > stats > LossyStack


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.stats;
5
6 import java.util.LinkedList JavaDoc;
7
8 /**
9  * 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 JavaDoc data = new LinkedList JavaDoc();
14   private final int maxDepth;
15
16   public LossyStack(int depth) {
17     if (depth < 1) { throw new IllegalArgumentException JavaDoc("stack depth must be greater than or equal to 1"); }
18     this.maxDepth = depth;
19   }
20
21   public synchronized void push(Object JavaDoc obj) {
22     // we could slightly optimize the mostRecent() call by specifically storing the reference
23
// to the last object added in a dedicated variable
24
data.addFirst(obj);
25     if (data.size() > maxDepth) {
26       data.removeLast();
27     }
28   }
29
30   public synchronized Object JavaDoc pop() {
31     if (data.isEmpty()) { throw new IllegalStateException JavaDoc("stack empty"); }
32     return data.removeFirst();
33   }
34
35   public synchronized Object JavaDoc[] toArray(Object JavaDoc[] type) {
36     return data.toArray(type);
37   }
38
39   public synchronized Object JavaDoc peek() {
40     if (data.isEmpty()) { return null; }
41     return data.getFirst();
42   }
43
44   public synchronized boolean isEmtpy() {
45     return data.isEmpty();
46   }
47
48   public synchronized int depth() {
49     return data.size();
50   }
51
52 }
53
Popular Tags