12

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?

Alexandru Chirila
  • 2,274
  • 5
  • 29
  • 40
  • 2
    Check this question http://stackoverflow.com/questions/1453295/timer-timertask-versus-thread-sleep-in-java – Adrián Jan 28 '13 at 11:48
  • 1
    @AdriánLópez ScheduledExecutorService is preferred in most cases vs. Timer. See for example: http://stackoverflow.com/a/2213153/829571 – assylias Jan 28 '13 at 11:53

2 Answers2

6

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • is this better than the Timer class http://docs.oracle.com/javase/6/docs/api/javax/swing/Timer.html ? Nevermind i see now that this is for Swing – Alexandru Chirila Jan 28 '13 at 11:53
  • ScheduledExecutorService is preferred in most cases vs. Timer. See for example: stackoverflow.com/a/2213153/829571 – assylias Jan 28 '13 at 11:54
  • @RexLakio There are 2 Timer classes: the one you found and another one in java.util.Timer which is a general purpose Timer. – assylias Jan 28 '13 at 11:55
4

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

rai.skumar
  • 10,309
  • 6
  • 39
  • 55