Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8323703

ScheduledExecutorService.schedule is not thread safe when delay is long enough

XMLWordPrintable

      A DESCRIPTION OF THE PROBLEM :
      Calling ScheduledExecutorService.schedule with a long delay concurrently with other calls to schedule prevents the other tasks from ever running.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Concurrently call ScheduledExecutorService.schedule with a long delay and a short delay. When the race condition is encountered, the task with the short delay will never run.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      The task with the short delay always runs.
      ACTUAL -
      The task with the short delay doesn't always run.

      ---------- BEGIN SOURCE ----------

      import java.util.Collection;
      import java.util.concurrent.*;
      import java.util.stream.Collectors;
      import java.util.stream.Stream;

      public class Main
      {
          public static void main(String[] args) throws ExecutionException, InterruptedException {
              ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

              Runnable task = () -> {};

              Runnable longDelayedTask = () -> scheduledExecutorService.schedule(task, Long.MAX_VALUE, TimeUnit.NANOSECONDS);

              int numberOfConcurrentThreads = 100; // The higher this is, the higher the chance of reproducing the bug

              Collection<Thread> threads =
                  Stream.generate(() -> new Thread(longDelayedTask))
                      .limit(numberOfConcurrentThreads)
                      .collect(Collectors.toList());

              threads.forEach(Thread::start); // Removing this line prevents the next scheduled task from hanging.

              ScheduledFuture<?> scheduledFuture = scheduledExecutorService.schedule(task, 0, TimeUnit.NANOSECONDS);

              scheduledFuture.get(); // waits for the task to finish, but sometimes it never even runs

              scheduledExecutorService.shutdownNow();
          }
      }

      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Synchronize calls to ScheduledExecutorService.schedule or don't use long delays (not sure what the max acceptable delay is).

      FREQUENCY : often


            vklang Viktor Klang
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved: