I am writing an algorithm that takes in messages and then determines whether they compliant with the established messaging rate.
For example, no more than 5 messages are to be sent in ANY 50 second window. Therefore, this window MUST be a rolling window.
I have implemented this token bucket algorithm from this post. However, I can't get it working consistently. It passes some test cases but not others, which makes me think there is a logic issue hidden somewhere in here.
Here is what I have so far:
public class Messaging {
//times in millis
double time_before;
double time_now;
double now;
double time_passed;
double allowance;
//constants
static double per = 50000; // 50 seconds
static double rate = 5; //5 messages
public Messaging(){
time_before = System.currentTimeMillis();
allowance = rate;
}
public void onEvent(){
time_now = System.currentTimeMillis();
time_passed = time_now - time_before;
time_before = time_now;
allowance += time_passed * (rate / per);
if (allowance > rate){
allowance = rate;
System.out.println("Reset Allowance");
}
if (allowance < 1.0){
System.out.println("Discard");
}else{
System.out.println("Forward message");
allowance -= 1.0;
}
}
This doesn't work though!
public static void main(String[] args) {
Messaging orders = new Messaging();
for (int i = 0; i < 10; i++) {
orders.onEvent();
try {
Thread.sleep(5000);
} catch (Exception ex) {
}
}
}
Running the code above gives this:
Forward message. Time: 1469830426910
Forward message. Time: 1469830431912
Forward message. Time: 1469830436913
Forward message. Time: 1469830441920
Forward message. Time: 1469830446929
Forward message. Time: 1469830451937
Forward message. Time: 1469830456939
Forward message. Time: 1469830461952
Forward message. Time: 1469830466962
Discard. Time: 1469830471970
Total time passed: 50067
Why is only the last message being discarded? Shouldn't allowance be decremented enough that it fails automatically after the 5th message?
I would like help with this particular implementation please. The actual implementation will be in a proprietary language that doesn't have queues, etc.