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

Alexandru Chirila picture Alexandru Chirila · Jan 28, 2013 · Viewed 9.5k times · Source

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?

Answer

assylias picture assylias · Jan 28, 2013

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.