1 16 package org.directwebremoting.util; 17 18 23 public class HitMonitor 24 { 25 30 public HitMonitor(int seconds) 31 { 32 hitLog = new long[seconds]; 33 } 34 35 38 public void recordHit() 39 { 40 synchronized (hitLog) 41 { 42 trimHitLog(); 43 hitLog[0]++; 44 } 45 } 46 47 52 public int getHitsInLastPeriod() 53 { 54 synchronized (hitLog) 55 { 56 trimHitLog(); 57 58 int count = 0; 59 for (int i = 0; i < hitLog.length; i++) 60 { 61 count += hitLog[i]; 62 } 63 64 return count; 65 } 66 } 67 68 72 private void trimHitLog() 73 { 74 long now = getCurrentTimestamp(); 75 int secondsPassedSinceLastHit = (int) (now - zeroTimestamp); 76 zeroTimestamp = now; 77 78 if (secondsPassedSinceLastHit > 0) 79 { 80 for (int i = hitLog.length - 1; i >= 0; i--) 82 { 83 if (i >= secondsPassedSinceLastHit) 84 { 85 hitLog[i] = hitLog[i - secondsPassedSinceLastHit]; 86 } 87 else 88 { 89 hitLog[i] = 0; 90 } 91 } 92 } 93 } 94 95 99 private long getCurrentTimestamp() 100 { 101 return System.currentTimeMillis() / 1000; 102 } 103 104 107 private long zeroTimestamp = getCurrentTimestamp(); 108 109 112 private final long[] hitLog; 113 } 114 | Popular Tags |