someone
someone

Reputation: 6572

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?

Upvotes: 5

Views: 2474

Answers (5)

Peter Lawrey
Peter Lawrey

Reputation: 533530

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.

Upvotes: 3

Steven Mastandrea
Steven Mastandrea

Reputation: 2772

Well, I don't think it would have memory issues (unless your doMyLogic method has memory issues), because any memory leaks will manifest themselves regardless of the delay. The real benefit of the sleep is that in most instances, the code doesn't need to be doMyLogic as fast as the computer can. For example, let's say doMyLogic is checking to see if a file was created in a directory. It would not be necessary to have the computer check several hundred times a second for that scenario (which would require a lot of CPU and disk I/O), when 1 time a second may be sufficient.

The biggest impact of not having the timing is using extra CPU time and other resources that your logic function has, in most cases with no discernable impact to the end user.

Upvotes: 2

Oleksi
Oleksi

Reputation: 13097

If you don't have a pause, your CPU is constantly doing something. You are effectively blocking the CPU. However, if you add a pause (sleep()) you give the CPU a break to do other things.

Upvotes: 2

icza
icza

Reputation: 417662

It's always a good practice to insert sleep in a (semi) infinite loop so when code execution reaches the sleep, other threads can be executed too.

Upvotes: 2

Michal Klouda
Michal Klouda

Reputation: 14521

Not memory issues, but you are blocking CPU. Definitely use a delay.

It also depends a bit on the doMyLogic() method.

Upvotes: 2

Related Questions