1 46 package org.mr.core.stats; 47 48 import org.mr.core.util.SystemTime; 49 50 58 public class TemporalCounter { 59 private long[] slots; 60 private long earliest; 61 private int startMark; 62 private long slotSizeMilli; 63 64 public TemporalCounter(long slotSizeMilli, int slotCount) { 65 this.slots = new long[slotCount]; 66 this.slotSizeMilli = slotSizeMilli; 67 this.earliest = SystemTime.currentTimeMillis() / slotSizeMilli; 68 this.startMark = 0; 69 } 71 public synchronized void addSample(long sample) { 72 long current = SystemTime.currentTimeMillis() / slotSizeMilli; 73 if ((int) (current - this.earliest) >= this.slots.length) { 74 int difference = 75 (int) (current - this.earliest) - this.slots.length + 1; 76 this.earliest += (long) difference; 77 if (difference > this.slots.length) { 78 difference = this.slots.length; 79 } 80 for (int i = 0; i < difference; i++) { 81 int slot = (this.startMark + i) % this.slots.length; 82 this.slots[slot] = 0; 83 } 84 this.startMark = (this.startMark + difference) % this.slots.length; 85 } 86 int index = (this.startMark + ((int) (current - this.earliest))) % 87 this.slots.length; 88 this.slots[index] += sample; 89 } 90 91 public synchronized long getValue() { 92 addSample((long) 0); 94 long value = 0; 95 for (int i = 0; i < this.slots.length; i++) { 96 value += this.slots[i]; 97 } 98 99 return value; 100 } 101 } | Popular Tags |