1 17 package org.apache.excalibur.event.impl; 18 19 import org.apache.excalibur.event.EnqueuePredicate; 20 import org.apache.excalibur.event.Sink; 21 22 28 public class RateLimitingPredicate implements EnqueuePredicate 29 { 30 31 private double m_targetRate; 32 33 34 private int m_depth; 35 36 private int m_tokenCount; 37 private long m_lastTime; 38 private double m_regenTimeMs; 39 40 41 private static final long MIN_REGENERATION_TIME = 0; 42 43 52 public RateLimitingPredicate(int depth) 53 { 54 this(-1.0, depth); 55 } 56 57 68 public RateLimitingPredicate(double targetRate, int depth) 69 { 70 m_targetRate = targetRate; 71 m_depth = depth; 72 73 m_regenTimeMs = (1.0 / targetRate) * 1.0e3; 74 if (m_regenTimeMs < 1) 75 { 76 m_regenTimeMs = 1; 77 } 78 79 m_tokenCount = depth; 80 m_lastTime = System.currentTimeMillis(); 81 } 82 83 87 public boolean accept(Object element, Sink sink) 88 { 89 if (m_targetRate == -1.0) 90 { 91 return true; 92 } 93 94 long currentTime = System.currentTimeMillis(); 96 long delay = currentTime - m_lastTime; 97 98 if (delay >= MIN_REGENERATION_TIME) 99 { 100 double numTokens = ((double) delay * 1.0) / (m_regenTimeMs * 1.0); 101 m_tokenCount += numTokens; 102 103 if (m_tokenCount > m_depth) 104 { 105 m_tokenCount = m_depth; 106 } 107 108 m_lastTime = currentTime; 109 } 110 111 if (m_tokenCount >= 1) 112 { 113 m_tokenCount--; 114 return true; 115 } 116 else 117 { 118 return false; 119 } 120 } 121 122 125 public boolean accept(Object [] elements, Sink sink) 126 { 127 if (m_targetRate == -1.0) 128 { 129 return true; 130 } 131 132 long currentTime = System.currentTimeMillis(); 134 long delay = currentTime - m_lastTime; 135 136 if (delay >= MIN_REGENERATION_TIME) 137 { 138 double numTokens = ((double) delay * 1.0) / (m_regenTimeMs * 1.0); 139 m_tokenCount += numTokens; 140 141 if (m_tokenCount > m_depth) 142 { 143 m_tokenCount = m_depth; 144 } 145 m_lastTime = currentTime; 146 } 147 148 if (m_tokenCount >= elements.length) 149 { 150 m_tokenCount -= elements.length; 151 return true; 152 } 153 else 154 { 155 return false; 156 } 157 } 158 159 167 public double getTargetRate() 168 { 169 return m_targetRate; 170 } 171 172 179 public int getDepth() 180 { 181 return m_depth; 182 } 183 184 191 public int getBucketSize() 192 { 193 return (int) m_tokenCount; 194 } 195 196 204 public void setTargetRate(double targetRate) 205 { 206 m_targetRate = targetRate; 207 208 m_regenTimeMs = (1.0 / targetRate) * 1.0e3; 209 if (m_regenTimeMs < 1) 210 { 211 m_regenTimeMs = 1; 212 } 213 } 214 215 222 public void setDepth(int depth) 223 { 224 m_depth = depth; 225 } 226 227 } 228 | Popular Tags |