True delayed

I usually use an infinite loop, as shown below:

public static boolean start = false; while(!start) { doMyLogic(); } 

but a friend said that you need to have a little delay inside the while-true loop (like below), otherwise it can cause memory problems, and is also not good practice.

The proposed method:

 while(!start) { Thread.sleep(few_miliseconds); // 500 ms doMyLogic(); } 

Please inform me about the impact of the proposed method. Am I doing it right?

+4
source share
5 answers

Well, I don’t think that I would have memory problems (unless your doMyLogic method has memory problems), because any memory leaks will occur regardless of the delay. The real benefit of sleep is that in most cases the code should not be doMyLogic as fast as a computer. For example, let's say doMyLogic checks if a file was created in a directory. There is no need for the computer to check several hundred times per second for this scenario (which would require a lot of CPU and disk I / O) when 1 time per second is enough.

The biggest impact of lack of time is the use of additional processor time and other resources that your logic function has, in most cases, without a noticeable effect on the end user.

+2
source

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

It also slightly depends on the doMyLogic() method.

+2
source

It is always useful to insert a dream in a (semi) infinite loop, so when the code reaches sleep, other threads can be executed.

+2
source

If you do not have a pause, your processor is constantly doing something. You effectively block the processor. However, if you add a pause (sleep ()), you give the processor a break for other things.

+2
source

I would use ScheduledExecutorService

 ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); service.scheduleAtFixedRate(new Runnable() { @Override public void run() { doMyLogic(); } }, 500, 500, TimeUnit.MILLISECONDS); 

This service can be reused for many repetitive or pending tasks and can be shutdown() as needed.

+2
source

Source: https://habr.com/ru/post/1442320/


All Articles