I have read some threads that said that calling Thread.sleep() in a loop is problematic and is a serious performance issue. But in some cases it seems the most natural thing to do.
For example if I want my application to do something every 3 minutes (lets say it's an autosave)
public void startAutosaveLoop(){
stop = false;
new Thread(new Runnable() {
@Override
public void run() {
while (!stop){
Thread.sleep(T*1000);
if (!stop){
// do something
}
}
}
}).start();
}
Is there a better way to doing this? Is this kind of situation problematic?
You need to write sleep() method whenever we need to make webdriver wait. So if you want to wait for two web elements, you need to write Thread. sleep() twice just before you locate web elements. It is not good programming practice.
Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.
Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t. sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.
TimeUnit provides a human-readable version of the Thread. sleep() method which can be used in place of the former. For a long time Thread's sleep() method is a standard way to pause a Thread in Java and almost every Java programmer is familiar with that.
If you sleep for a long time it won't affect the performance. If you sleep for 5ms, check some condition, go back to sleep for 5 ms etc. for 3 minutes it will have some performance cost.
If what you need is to do something every 3 minutes, it would make more sense to use a scheduler instead.
You can have a look at the javadoc of ScheduledExecutorService for a very similar example.
You should better use ScheduledExecutorService if you want to put delay. This interface supports future and/or periodic execution of task.
Pls check API doc for sample code and details: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html
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