javascheduledexecutorservice

scheduled executor accuracy


I am having a problem with the ScheduledExecutorService in java (I didn't face this problem a couple of days back is what makes it strange for me). Please find the code below and the console output. The delay between executing the task repeatedly is 1 ms so I should ideally be reaching the count of 1000 every second (give or take a few milliseconds) but this is just not happening. Please help..

CODE:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class SchedulerTest {

     private static final ScheduledExecutorService executor =       Executors.newScheduledThreadPool(2);
     static DateFormat df= new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SSS");

     private static class TestRunnable1 implements Runnable{
         private int count=0;

         @Override
          public void run() {
           count++;
           if(count1 % 1000==0){
              System.out.println(count1+"  "+df.format(Calendar.getInstance().getTime()));
            }
     
         }
    }

  
   public static void main(String[] args){
      Runnable localService = new TestRunnable1();
      try{
           executor.scheduleWithFixedDelay(localService, 0, 1, TimeUnit.MILLISECONDS);
         }catch(Exception e){
           e.printStackTrace();
        }
   }
 }

CONSOLE OUTPUT

1000 13-Mar-2013 14:43:54.477
2000 13-Mar-2013 14:44:10.296
3000 13-Mar-2013 14:44:26.381
4000 13-Mar-2013 14:44:42.621
5000 13-Mar-2013 14:44:55.907
6000 13-Mar-2013 14:44:58.516
7000 13-Mar-2013 14:45:05.896
8000 13-Mar-2013 14:45:10.292
9000 13-Mar-2013 14:45:15.129
10000 13-Mar-2013 14:45:18.187

Solution

  • You want to use ScheduledExecutorService#scheduleAtFixedRate rather than ScheduledExecutorService#scheduleWithFixedDelay.

    If you schedule with a fixed delay, then 1 ms must elapse between the time that the last execution completed and the time that the next execution begins. So the wall-clock time that it takes to complete 1000 iterations will be, at a minimum, 1 second plus the execution time of the thousand iterations.