Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while true with delay

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?

like image 892
someone Avatar asked Oct 26 '12 14:10

someone


People also ask

Is it OK to use while true?

"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.

What is a while true loop called?

while True: ... means infinite loop. The while statement is often used of a finite loop.

How do you make a while loop always true?

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.


1 Answers

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.

like image 132
Peter Lawrey Avatar answered Oct 11 '22 11:10

Peter Lawrey