Why ScheduledThreadPoolExecutor is not respecting the delay?

I have a Customized implementation for ScheduledThreadPoolExecutor using which I am trying to execute a task for continuous execution. The problem I have faced here with the implementation is, some tasks executed continuously where as two of them are not respecting the delay and executed continuously. I am using the scheduleWithFixedDelay method.
Even I have tried reproducing, but I couldn't.
Here is my customized implementation.
package com.portware.utils.snapmarketdata.test;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import com.indigo.utils.Log;
* To schedule the tasks in timely manner.
public class TestScheduledExecutorService  {
  private static String CLASS_NAME = TestScheduledExecutorService.class.getName();
  protected final ThreadPoolExecutor executor;
  static int totalCount = 0;
  public static void main(String[] args) throws InterruptedException {
    TestScheduledExecutorService executorService = new TestScheduledExecutorService("Test", 10, null);
    final AtomicInteger integer = new AtomicInteger();
    final Set<Integer> testSet = new HashSet<Integer>();
    for (int i = 0; i < 10; i++) {
      testSet.add(i);
    Iterator<Integer> iterator = testSet.iterator();
    synchronized (testSet) {
    while(iterator.hasNext()) {
      integer.set(iterator.next());
      executorService.submitTaskForContinuousExecution(new Runnable() {
      @Override
      public void run() {
          System.out.println(Thread.currentThread().getName()+" Hello : "+integer.get() + " count value is:"+totalCount++);
    }, integer.toString());
    while (true) {
      synchronized (TestScheduledExecutorService.class) {
        TestScheduledExecutorService.class.wait();
  private static class MyRunnableTask implements Runnable{
    ScheduledFuture<?> future;
     * The task to be run.
    private Runnable runnable;
     * The number of attempt.
    private int count;
     * Maximum attempts configured under TCA configuration.
    private int maximumAttempts;
    private String id;
    public MyRunnableTask(Runnable runnable, int maximumAttempts, String id) {
      this.runnable = runnable;
      this.maximumAttempts = maximumAttempts;
      this.id = id;
    @Override
    public void run() {
      if (count >= maximumAttempts) {
        this.future.cancel(true);
        System.out.println("Cancelling the task with id :"+id+" after count :"+count);
        return;
      count++;
      this.runnable.run();
     * Return the number of attempt.
     * @return
    public int getCount() {
      return count;
  private void submitTaskForContinuousExecution(Runnable runnable, String id){
    int numOfAttempts = 10;
    MyRunnableTask runnableTask = new MyRunnableTask(runnable, numOfAttempts, id);
    int interval = 1;
    ScheduledFuture<?> scheduleWithFixedDelay = this.scheduleWithFixedDelay(runnableTask, 0, TimeUnit.SECONDS.toMillis(interval), TimeUnit.MILLISECONDS);
    if(id != null) {
      /*System.out.println("Submitted the task for continuous execution for the ticket id :"+id+"  with maximum attempts : "+numOfAttempts
          + " and interval : "+ interval);*/
      runnableTask.future = scheduleWithFixedDelay;
   * Creates an Executor Service to provide customized execution for tasks to be scheduled.
   * @param threadName is the name that shows in logs.
   * @param maximumThreads is the number of threads can be created.
   * @param rejectedExecutionHandler is if the Queue reaches it's maximum capacity and all the executor gives
   * the tasks to rejectedExecutionHandler.
  public TestScheduledExecutorService(String threadName, int maximumThreads, RejectedExecutionHandler rejectedExecutionHandler) {
    this.executor = createExecutor(threadName, maximumThreads, rejectedExecutionHandler);
  protected ThreadPoolExecutor createExecutor(String threadName, int minimumThreads, RejectedExecutionHandler rejectedExecutionHandler) {
    ThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(minimumThreads)
      @Override
      protected void beforeExecute(Thread t, Runnable r) {
        TestScheduledExecutorService.this.beforeExecute(t, r);
        this.purge();
      @Override
      protected void afterExecute(Runnable r, Throwable t) {
        TestScheduledExecutorService.this.afterExecute(r, t);
    if(rejectedExecutionHandler != null) {
      threadPoolExecutor.setRejectedExecutionHandler(rejectedExecutionHandler);
    }else{
      threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    threadPoolExecutor.setThreadFactory(new TestThreadFactory(threadName, threadPoolExecutor));
    threadPoolExecutor.setKeepAliveTime(120, TimeUnit.SECONDS);
    threadPoolExecutor.allowCoreThreadTimeOut(true);
    return threadPoolExecutor;
   * Executes the task repeatedly with the given delay
   * @param task
   * @param initialDelay
   * @param delay
   * @param unit
   * @return
  public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, int initialDelay, long delay, TimeUnit unit) {
    return ((ScheduledThreadPoolExecutor)executor).scheduleWithFixedDelay(task, initialDelay, delay, unit);
   * To provide threads with specific features.
  protected static class TestThreadFactory implements ThreadFactory {
    private ThreadFactory threadFactory = Executors.defaultThreadFactory();
    private ThreadPoolExecutor threadPoolExecutor;
    private String groupName;
    public TestThreadFactory(String groupName, ThreadPoolExecutor threadPoolExecutor) {
      this.groupName = groupName;
      this.threadPoolExecutor = threadPoolExecutor;
    @Override
    public Thread newThread(Runnable r) {
      Thread thread = threadFactory.newThread(r);
      int activeCount = this.threadPoolExecutor.getPoolSize();
      activeCount++;
      thread.setName(this.groupName+"-"+activeCount);
      thread.setDaemon(true);
      return thread;
   * Performs initialization tasks before starting this thread.
   * @param thread
   * @param runnable
  protected void beforeExecute(Thread thread, Runnable runnable){
   * Performs tasks after execution of this runnable.
   * @param thread
   * @param runnable
  protected void afterExecute(Runnable runnable, Throwable t){
   * Initiates an orderly shutdown in which previously submitted
   * tasks are executed, but no new tasks will be
   * accepted. Invocation has no additional effect if already shut
   * down.
  public void shutdown() {
    if(this.executor != null) {
      Log.notice(CLASS_NAME, "shutdown", "Shutting down Executor Service");
      this.executor.shutdown();
   * Attempts to stop all actively executing tasks, halts the
   * processing of waiting tasks, and returns a list of the tasks
   * that were awaiting execution. These tasks are drained (removed)
   * from the task queue upon return from this method.
   * <p>There are no guarantees beyond best-effort attempts to stop
   * processing actively executing tasks.  This implementation
   * cancels tasks via {@link Thread#interrupt}, so any task that
   * fails to respond to interrupts may never terminate.
  public List<Runnable> shutdownNow() {
   if(this.executor != null) {
     Log.notice(CLASS_NAME, "shutdownNow", "Immediately shutting down Executor Service");
     try {
      return this.executor.shutdownNow();
    } catch (Exception e) {
      Log.notice(CLASS_NAME, "shutdownNow", e.getMessage());
   return Collections.emptyList();
   * Returns a Future for the given runnable task.
  public Future<?> submit(Runnable runnable) {
    if(this.executor != null) {
      return this.executor.submit(runnable);
    return null;
Is there any possibility for the continuous execution or not?

I have a Customized implementation for ScheduledThreadPoolExecutor using which I am trying to execute a task for continuous execution. The problem I have faced here with the implementation is, some tasks executed continuously where as two of them are not respecting the delay and executed continuously. I am using the scheduleWithFixedDelay method.
Even I have tried reproducing, but I couldn't.
Here is my customized implementation.
package com.portware.utils.snapmarketdata.test;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import com.indigo.utils.Log;
* To schedule the tasks in timely manner.
public class TestScheduledExecutorService  {
  private static String CLASS_NAME = TestScheduledExecutorService.class.getName();
  protected final ThreadPoolExecutor executor;
  static int totalCount = 0;
  public static void main(String[] args) throws InterruptedException {
    TestScheduledExecutorService executorService = new TestScheduledExecutorService("Test", 10, null);
    final AtomicInteger integer = new AtomicInteger();
    final Set<Integer> testSet = new HashSet<Integer>();
    for (int i = 0; i < 10; i++) {
      testSet.add(i);
    Iterator<Integer> iterator = testSet.iterator();
    synchronized (testSet) {
    while(iterator.hasNext()) {
      integer.set(iterator.next());
      executorService.submitTaskForContinuousExecution(new Runnable() {
      @Override
      public void run() {
          System.out.println(Thread.currentThread().getName()+" Hello : "+integer.get() + " count value is:"+totalCount++);
    }, integer.toString());
    while (true) {
      synchronized (TestScheduledExecutorService.class) {
        TestScheduledExecutorService.class.wait();
  private static class MyRunnableTask implements Runnable{
    ScheduledFuture<?> future;
     * The task to be run.
    private Runnable runnable;
     * The number of attempt.
    private int count;
     * Maximum attempts configured under TCA configuration.
    private int maximumAttempts;
    private String id;
    public MyRunnableTask(Runnable runnable, int maximumAttempts, String id) {
      this.runnable = runnable;
      this.maximumAttempts = maximumAttempts;
      this.id = id;
    @Override
    public void run() {
      if (count >= maximumAttempts) {
        this.future.cancel(true);
        System.out.println("Cancelling the task with id :"+id+" after count :"+count);
        return;
      count++;
      this.runnable.run();
     * Return the number of attempt.
     * @return
    public int getCount() {
      return count;
  private void submitTaskForContinuousExecution(Runnable runnable, String id){
    int numOfAttempts = 10;
    MyRunnableTask runnableTask = new MyRunnableTask(runnable, numOfAttempts, id);
    int interval = 1;
    ScheduledFuture<?> scheduleWithFixedDelay = this.scheduleWithFixedDelay(runnableTask, 0, TimeUnit.SECONDS.toMillis(interval), TimeUnit.MILLISECONDS);
    if(id != null) {
      /*System.out.println("Submitted the task for continuous execution for the ticket id :"+id+"  with maximum attempts : "+numOfAttempts
          + " and interval : "+ interval);*/
      runnableTask.future = scheduleWithFixedDelay;
   * Creates an Executor Service to provide customized execution for tasks to be scheduled.
   * @param threadName is the name that shows in logs.
   * @param maximumThreads is the number of threads can be created.
   * @param rejectedExecutionHandler is if the Queue reaches it's maximum capacity and all the executor gives
   * the tasks to rejectedExecutionHandler.
  public TestScheduledExecutorService(String threadName, int maximumThreads, RejectedExecutionHandler rejectedExecutionHandler) {
    this.executor = createExecutor(threadName, maximumThreads, rejectedExecutionHandler);
  protected ThreadPoolExecutor createExecutor(String threadName, int minimumThreads, RejectedExecutionHandler rejectedExecutionHandler) {
    ThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(minimumThreads)
      @Override
      protected void beforeExecute(Thread t, Runnable r) {
        TestScheduledExecutorService.this.beforeExecute(t, r);
        this.purge();
      @Override
      protected void afterExecute(Runnable r, Throwable t) {
        TestScheduledExecutorService.this.afterExecute(r, t);
    if(rejectedExecutionHandler != null) {
      threadPoolExecutor.setRejectedExecutionHandler(rejectedExecutionHandler);
    }else{
      threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    threadPoolExecutor.setThreadFactory(new TestThreadFactory(threadName, threadPoolExecutor));
    threadPoolExecutor.setKeepAliveTime(120, TimeUnit.SECONDS);
    threadPoolExecutor.allowCoreThreadTimeOut(true);
    return threadPoolExecutor;
   * Executes the task repeatedly with the given delay
   * @param task
   * @param initialDelay
   * @param delay
   * @param unit
   * @return
  public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, int initialDelay, long delay, TimeUnit unit) {
    return ((ScheduledThreadPoolExecutor)executor).scheduleWithFixedDelay(task, initialDelay, delay, unit);
   * To provide threads with specific features.
  protected static class TestThreadFactory implements ThreadFactory {
    private ThreadFactory threadFactory = Executors.defaultThreadFactory();
    private ThreadPoolExecutor threadPoolExecutor;
    private String groupName;
    public TestThreadFactory(String groupName, ThreadPoolExecutor threadPoolExecutor) {
      this.groupName = groupName;
      this.threadPoolExecutor = threadPoolExecutor;
    @Override
    public Thread newThread(Runnable r) {
      Thread thread = threadFactory.newThread(r);
      int activeCount = this.threadPoolExecutor.getPoolSize();
      activeCount++;
      thread.setName(this.groupName+"-"+activeCount);
      thread.setDaemon(true);
      return thread;
   * Performs initialization tasks before starting this thread.
   * @param thread
   * @param runnable
  protected void beforeExecute(Thread thread, Runnable runnable){
   * Performs tasks after execution of this runnable.
   * @param thread
   * @param runnable
  protected void afterExecute(Runnable runnable, Throwable t){
   * Initiates an orderly shutdown in which previously submitted
   * tasks are executed, but no new tasks will be
   * accepted. Invocation has no additional effect if already shut
   * down.
  public void shutdown() {
    if(this.executor != null) {
      Log.notice(CLASS_NAME, "shutdown", "Shutting down Executor Service");
      this.executor.shutdown();
   * Attempts to stop all actively executing tasks, halts the
   * processing of waiting tasks, and returns a list of the tasks
   * that were awaiting execution. These tasks are drained (removed)
   * from the task queue upon return from this method.
   * <p>There are no guarantees beyond best-effort attempts to stop
   * processing actively executing tasks.  This implementation
   * cancels tasks via {@link Thread#interrupt}, so any task that
   * fails to respond to interrupts may never terminate.
  public List<Runnable> shutdownNow() {
   if(this.executor != null) {
     Log.notice(CLASS_NAME, "shutdownNow", "Immediately shutting down Executor Service");
     try {
      return this.executor.shutdownNow();
    } catch (Exception e) {
      Log.notice(CLASS_NAME, "shutdownNow", e.getMessage());
   return Collections.emptyList();
   * Returns a Future for the given runnable task.
  public Future<?> submit(Runnable runnable) {
    if(this.executor != null) {
      return this.executor.submit(runnable);
    return null;
Is there any possibility for the continuous execution or not?

Similar Messages

  • KEYNOTE: Why change the format of the presentations? not respect the original format!

    Why change the format of the presentations? Keynote not respect the original format!
    This new versionof Keynot (6.1-1769) is very poor:
    is very slow
    missing fonts
    changes the selected letters
    change the formats of the presentations
    Carousel animations missing
    Please correct the defects before releasing a new version. (The previous version was much better).

    Found the solution!
    I must set the Formats in the CODEC to get the Format that I want to play with! I was trying to complicate too much!
    The correct format class to is RGBFormat.
    RGB

  • Why am I not getting the buttons of Hide/Show, Refresh, Back, Home, Options ?

    Gorgeous Hello All,
    If anyone of you can please provide me a solution for the following, will help me in plentious and galore.
    Am using Adobe RoboHelp, Version 10 and IE version being 10.
    A hurdle :-
    When I File -> View -> Primary Layout : I am getting only these options of Search, Hide, Contents, Index, Glossary, Print being displayed on the screen, eventhough I have ticked for Hide/Show, Refresh, Back, Home (Home -> Advanced Properties -> Home : and declared the respective url as well) , Options  courtesy View -> Pods -> Project Set-up -> Double Click on Windows -> Double Click on NewWindow.
    Why am I not getting the buttons of Hide/Show, Refresh, Back, Home, Options when I File -> View -> Primary Layout ?
    Cheese - Vipin Nambiar

    Hey Piyush Buddy, where were you since my morning !!! :-) :-) :-)   Your simple question here made me realize where did I make the slip of my brain and now all the desired buttons are appearing on my screen. 
    I just made simple parameter changes called View -> Pods -> Single Source Layouts -> Right Click On Microsoft HTML Help -> Setted as Primary Layout (earlier my Primary Layout was setted up for Multiscreen HTML 5).
    THANKS GALORE Piyush buddy - Your simple question to me made a mammoth and galores of help to get my train on track.

  • Why i can not see the columns of "Tax Category" in transaction code FS00

    Dear Experts,
          Why i can not see the columns of "Tax Category" and "Posting without tax allowed" in tab of "Control Data"  transaction code FS00?
           How can i add the columns of "Tax Category" and "Posting without tax allowed"?
    Looking forward to your reply.
    Best Regards,
    Merry

    Hi,
    Go to transaction OBD4, and check whether the field "Tax category" is suppressed in group "Account control" for your GL account group.
    If not, then go to OB26 and check the field status for the same field for create, change activity.
    Regards,
    Gaurav

  • Why can I not disable the guest user in the 10.8.2 update? I have never enabled the guest user, but after the update, it was automatically enabled with a "managed" tag. It is not selectable even after entering my admin password to unlock the options.

    Why can I not disable the guest user in the 10.8.2 update? I have never enabled the guest user, but after the update, it was automatically enabled with a "managed" tag. It is not selectable even after entering my admin password to unlock the options. I was able to select the account under "parental controls", but again, could not delete it. Why Apple? Why?!!????

    SOLVED Ok. I actually was able to disable it. I had to actually log in as the guest user to make it accessible in the preference window. Then I disabled it and logged out. Apologies if this was obvious for some people, but I have had some sort of issue with something every update since Snow Leopard.

  • I have upgrade ios 6 to ios7 on my iphone 5.  I do NOT like it.  I want to come back to the previosu version.  why is it so complicated.  Why can I not find the instruction strait from apple? This is the worst possible upgrade ever.

    I have upgrade ios 6 to ios7 on my iphone 5.  I do NOT like it at all.   I want to come back to the previous version.  why is it so complicated? Why can I not find the instruction strait from apple? This is the worst possible upgrade ever.  It make me think of when ericsson got sold to Sony....drastic PC change.
    I would like to have simple instruction on how to downgrade.
    It feel like a change that I did not ask for , ok I push the upgrade buttom, but really this is the worst update aver!
    HELP!

    iPhone User Guide (For iOS 7 Software)Sep 20, 2013 - 23 MB

  • Why can I not check the 'shuffle images' box in a slide show settings in iPhoto 9.6?

    Why can I not check the 'Shuffle images' box in settings of a slide show in iPhoto 9.6? All other settings I can check but this one.

    Hey Brad,
    If you are unable to select the shuffle images checkbox, follow the steps in this article -
    iPhoto '11: Change slideshow settings
    Specifically -
    To display slides in random order, select “Shuffle slide order.” If you don’t see this option, play the slideshow, move the pointer to make the slideshow controls appear, and then click the Settings button.
    Thanks for using Apple Support Communities.
    Be well,
    Brett L 

  • After importing images from my card using LR 5.4, the GPS data does not show in the metadata panel. However, when I look at the imported images using Bridge, the GPS data is visible. Anybody know why LR is not seeing the GPS data? Camera is Canon 6D.

    After importing images from my card using LR 5.4, the GPS data does not show in the metadata panel. However, when I look at the imported images using Bridge, the GPS data is visible. Anybody know why LR is not seeing the GPS data? Camera is Canon 6D.

    Ok, the issue seem to be solved. The problem was this:
    The many hundred files (raw and xmp per image) have been downloaded by ftp in no specific order. Means - a couple of files in the download queue - both raw and xmps. Most of the time, the small xmp files have been finished loading first and hence the "last change date" of these xmp files was OLDER than the "last change date" of the raw file - Lightroom then seem to ignore the existence of the xmp file and does not read it during import.(a minute is enough to run into the problem)
    By simply using the ftp client in a way that all large raw files get downloaded first followed by the xmp files, we achieved that all "last changed dates" of the xmp files are NEWER than the related raw files. (at least not older)
    And then LR is reading them and all metadata information has been set / read correctly.
    So this is solved.

  • Adobe acrobat 7.0 standard, I went online to install, why would it not accept the serial no?

    adobe acrobat 7.0 standard, why would it not accept the serial number?

    THIS IS THE ERROR MESSAGE: -
    Invalid Serial Number
    < Removed by Moderator >
    Invalid Serial Number. This is not a valid serial number. Please go back and re-enter your serial number.
    The serial number above is the serial number on the disk which I purchased some years ago.
    Can you please help?
    Message was edited by: Moderator

  • HT204406 I have subscribed to match on iTunes and organized my music on my Mac Book.  Why does it not appear the same way on my iPad

    I would like my music to appear organized in the same way on my iPad as I have done it on my Mac Book.  (and on my iPhone as well)  Since it is in the cloud, why does it not appear the same way in all devices?

    The purpose of iTunes match is to make your music library available to all of your devices anywhere. It will sync Playlists, but no other type of organization you may have made.
    If you're having trouble, be sure you are logged into the same Apple ID on all devices but be sure to read this article and pay special attention to associating your devices with an Apple ID. There are important restrictions you should know about.

  • Why can I not import the videos from my iPhone 4 onto my desktop (Windows Vista)? When I plug in it imports the photos without a problem but it doesn't seem to import the videos.

    Why can I not import the videos from my iPhone 4 onto my desktop (Windows Vista)? When I plug in it imports the photos without a problem but it doesn't seem to import the videos.

    1.Download the Flash setup file from here: <br />
    [http://fpdownload.adobe.com/get/flashplayer/current/install_flash_player.exe Adobe Flash - Plugin version]. <br />
    Save it to your Desktop.<br />
    2. Close Firefox using File > Exit <br />
    then check the Task Manager > Processes tab to make sure '''firefox.exe''' is closed, <br />
    {XP: Ctrl+Alt+Del, Vista: Shift+Ctrl+ESC = Processes tab}
    3. Then run the Flash setup file from your Desktop.
    * On Vista and Windows 7 you may need to run the plugin installer as Administrator by starting the installer via the right-click context menu if you do not get an UAC prompt to ask for permission to continue (i.e nothing seems to happen). <br />
    See this: <br />
    [http://vistasupport.mvps.org/run_as_administrator.htm]

  • Why can I not use the channel name, which is obtained from the function of DAQmx Task, as the input of the channel name for the function of Get Channel Information of DAQ?

    Why can I not use the channel name, which is obtained from the function of DAQmx Task, as the input of the channel name for the function of Get Channel Information of DAQ?

    Not a lot of details here, but my guess is this isn't working for you because you are wiring in the task to the Active Channels Property and not the actual Channel Name. I have attatched a screenshot of what I believe you are trying to do. The Task has 2 channels in it, so I need to index off one of the channels and wire it into the active channels input of the Channel Property node. Then I can read information about that channel
    Attachments:
    channel_name.JPG ‏69 KB

  • Why can I not adjust the volume on a video when accessed from the lock screen

    Why can I not adjust the volume of a video in my pictures folder, when accessed from the new lock screen option?

    There is no way to access videos directly from the lock screen.
    What exactly is being attempted here?

  • HT204406 Why am I not given the option to authorise my computer to use icloud

    Why am I not given the option to authorise my computer to use icloud

    Apple ID security issues -
    Call Apple Care and ask for the Account Security Team. They can assist you with your issue.

  • Why Apple will not open the shop in Russia?

    Why Apple will not open the Apple Store in Russia?

    Welcome to the Support Communities. This article is from about a year ago:
    Apple to open its own stores in Russia
    ...Found HERE.

Maybe you are looking for