What is the best practice to measure amount in time? I have a multithreading application. Thread can be any number. I want to perform N times operation per second. I tried several techniques but still have no 100% success. Here is a snippet and you might see the problem more clearly.
To be more clear I want to send max 100 messages within one second(1000 millis). E.g If those threads are able to do it within 450 millis then I want to force all threads to wait 550 millis and then do the same operation again and again. I call this speedLimitMetter.getWaitTime() from threads. If it gives X > 0 then I force thread to wait X millis.
Any hint will be helpful
public class SpeedLimitMeter {
private int speedLimit;
private volatile int messageCounter = 0;
private volatile long firstTime = 0;
private volatile long lastTime = 0;
private volatile long waitTime = 0;
private volatile long waitUntil = 0;
public SpeedLimitMeter(int speedLimit) {
this.speedLimit = speedLimit;
}
public synchronized long getWaitTime() {
long currTime = System.currentTimeMillis();
if (messageCounter == speedLimit) {
if (waitTime == 0) {
long elapedTime = currTime - firstTime;
if (elapedTime < 1000) {
waitTime = 1000 - elapedTime;
waitUntil = currTime + waitTime;
return waitTime;
}
reset();
} else if (currTime < waitUntil) {
return waitTime;
} else {
reset();
}
}
if (messageCounter == 0) firstTime = currTime;
lastTime = currTime;
messageCounter++;
return 0;
}
private synchronized void reset() {
firstTime = 0;
lastTime = 0;
waitTime = 0;
waitUntil = 0;
messageCounter = 0;
}
}