Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to use Thread.sleep() in a loop in Java, to do something at regular intervals?

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?

like image 718
Alexandru Chirila Avatar asked Jan 28 '13 11:01

Alexandru Chirila


People also ask

Do you use thread sleep () frequently?

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.

Is it safe to use thread sleep in Java?

Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.

Can sleep () method causes another thread to sleep?

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.

What can be used instead of thread sleep in Java?

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.


2 Answers

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.

like image 156
assylias Avatar answered Oct 21 '22 15:10

assylias


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

like image 4
rai.skumar Avatar answered Oct 21 '22 14:10

rai.skumar