I normally use infinite loop as in the way below:
public static boolean start = false;
while(!start) {
doMyLogic();
}
but a friend said you need to have a small delay inside the while-true loop (like bellow), otherwise it may tend to cause memory issues and also it is not a good practice.
Suggested way:
while(!start) {
Thread.sleep(few_miliseconds); // 500 ms
doMyLogic();
}
Kindly advise me the impact of suggested way. Am I doing it right?
"while True" in itself is not bad practice/style, but using a "while True" loop in conjunction with a "break" could be considered bad practice because it can almost always be rewritten as a "while something" loop, which improves readability and maintainability.
while True: ... means infinite loop. The while statement is often used of a finite loop.
Instead of writing a condition after the while keyword, we just write the truth value directly to indicate that the condition will always be True . The loop runs until CTRL + C is pressed, but Python also has a break statement that we can use directly in our code to stop this type of loop.
I would use a ScheduledExecutorService
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
doMyLogic();
}
}, 500, 500, TimeUnit.MILLISECONDS);
This service can be re-used for many repeating or delayed tasks and can be shutdown()
as required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With