3 Replies Latest reply: Jul 29, 2008 11:41 PM by 807589 RSS

    Thread.sleep vs Timer

    803046
      During startup of application, a thread is started and loop and stop every 8 seconds with thread.sleep as below:

      ...
      Thread r = new Thread(new ReaderRunner(), "Reader Thread");
      r.start();          
      ....

      private class ReaderRunner implements Runnable {
      public void run() {
      while(running){
      try{

      //do something
      Thread.sleep(8000);

      }catch(Exception e){
      }
      }
      }
      }

      ...

      But i hav found out that using timer oso can achieve this:

      public class RunApp extends TimerTask {
      ...
      private void start(){
      Timer client = new Timer();
      client.scheduleAtFixedRate(this, 50, 8000);
      }
           
      ...

      public void run() {
      //do something                    
      }
      }

      I would like to ask whether both ways above are acting the same or differently in terms of performance? which of the both is encouraged to use? or any tool to test it out? Please advice....

      Thanks

      Edited by: whkhoo on Jul 29, 2008 6:20 PM

      Edited by: whkhoo on Jul 29, 2008 6:25 PM
        • 1. Re: Thread.sleep vs Timer
          807589
          That's a really interesting question!

          I can't find any documentation on this at all, and a modest attempt at performance testing suggests that neither method has a performance advantage.

          The timer task method strikes me as being slightly more vulnerable to unexpected performance hits than sleep due to the number of moving parts involved.
          • 2. Re: Thread.sleep vs Timer
            585441
            From an initial look at the Timer class, it looks like there is far more overhead in using the scheduleAtFixedRate method, than there would be using Thread.sleep, plus I think that Thread.sleep is simply more intuitive for the developer to read and maintain.

            Also, I think timer tasks are mainly used to perform a specified task at a given time interval (or Date). So the Thread.sleep and the Timer.scheduleAtFixedRate methods actually do different things, and you would hence, use them differently...

            JMeter is a good commonly used tool for performance testing:
            http://jakarta.apache.org/jmeter/

            HTH
            Mark
            • 3. Re: Thread.sleep vs Timer
              807589
              You can easily schedule multiple tasks on a single timer thread,.so they scale better.