1 4 package demo.jmx; 5 6 import java.util.LinkedList ; 7 import java.util.List ; 8 9 12 public class HistoryQueue 13 implements IHistory 14 { 15 private static final int DEFAULT_INTERVAL = 30; 16 17 private final long granularity; 18 private final int capacity; 19 private final List buffer = new LinkedList (); 20 21 private boolean enabled = true; 22 23 public HistoryQueue() 24 { 25 this(DEFAULT_INTERVAL, 24 * 60 * 60 / DEFAULT_INTERVAL); } 27 28 public HistoryQueue(int granularity, int capacity) 29 { 30 this.granularity = granularity * 1000; 31 this.capacity = capacity; 32 } 33 34 36 public String [] getHistory() 37 { 38 synchronized(this.buffer) 39 { 40 String [] history = new String [this.buffer.size()]; 41 for(int i = 0; i<history.length; i++) 42 { 43 HistoryData data = (HistoryData) this.buffer.get(i); 44 history[i] = data.toString(); 45 } 46 return history; 47 } 48 } 49 50 public boolean getEnabled() 51 { 52 return this.enabled; 53 } 54 55 public void setEnabled(boolean enabled) 56 { 57 synchronized(this) 58 { 59 this.enabled = enabled; 60 } 61 } 62 63 public void reset() 64 { 65 synchronized(this.buffer) 66 { 67 this.buffer.clear(); 68 } 69 } 70 71 public void updateHistory(int duration, String error) 72 { 73 if(this.enabled) 74 { 75 synchronized(this) 76 { 77 HistoryData historyData = getHistoryData(System.currentTimeMillis()); 78 historyData.update(duration, error); 79 } 80 } 81 } 82 83 private HistoryData getHistoryData(long time) 84 { 85 HistoryData data = (HistoryData) peek(); 86 87 long intervalStart = time - (time % granularity); 88 89 if(data == null) 90 { 91 data = new HistoryData(intervalStart, 0); 92 add(data); 93 } 94 else 95 { 96 if(time - data.getIntervalStart() > granularity) 97 { 98 data = new HistoryData(intervalStart, 0); 99 add(data); 100 } 101 } 102 return data; 103 } 104 105 110 private Object add(Object o) 111 { 112 Object removed = null; 113 if(this.buffer.size() >= this.capacity) removed = this.buffer.remove(0); 114 this.buffer.add(o); 115 return removed; 116 } 117 118 private Object peek() 119 { 120 final int size = this.buffer.size(); 121 return size == 0 ? null : this.buffer.get(size - 1); 122 } 123 } 124 | Popular Tags |