Search code examples
javaloopstimewhile-loop

Print only a certain amount of statements every second in Java


I have a while loop that prints a statement indefinitely but I want to make sure the statement only gets printed a maximum of a certain number of times every second.

What I tried doing was to add a Thread.sleep(1000 / maxMessagesPerSecond) after every print statement in the while loop but I'm not sure if it's the most efficient way or if it works all the time.


Solution

  • It works and could be an acceptable solution.

    However consider following:

    1. Execute that code in an appropriate thread. Details depends on what your application is. Just remember that while in a loop that thread wouldn't do anything else.
    2. With 1000 / maxMessagesPerSecond you get a floor-rounded value. So you could get more than maxMessagesPerSecond messages per second.
    3. If you a looking for a hight precision, remember that you would get an accumulating error: printing the message takes some time. So each following print would happen in with a bit higher period than 1000 / maxMessagesPerSecond. In a long run this tiny lags could end with a noticeable deviation.
    4. Consider using Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate()