Close

Java - ScheduledFuture Interface

[Updated: Oct 4, 2018, Created: Oct 4, 2018]

The interface java.util.concurrent.ScheduledFuture<V> extends Future<V> and Delayed interfaces. It represents the result of an asynchronous delayed computation.

Delayed interface represents a delay. Following is its snippet:

package java.util.concurrent;

public interface Delayed extends Comparable<Delayed> {
    long getDelay(TimeUnit unit);
}

All methods in ScheduledExecutorService return ScheduledFuture.

Examples

package com.logicbig.example;

import java.util.concurrent.*;

public class ScheduledFutureExample {
  public static void main(String[] args) throws ExecutionException, InterruptedException {
      ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
      ScheduledFuture<Long> scheduleFuture = ses.schedule(new Callable<Long>() {
          @Override
          public Long call() throws Exception {
              System.out.println("returning result");
              return ThreadLocalRandom.current().nextLong();
          }
      }, 2, TimeUnit.SECONDS);
      //remaining delay
      long delay = scheduleFuture.getDelay(TimeUnit.SECONDS);
      System.out.println("task scheduled");
      System.out.println("remaining delay: " + delay);
      Long result = scheduleFuture.get();
      System.out.println(result);
      ses.shutdown();

  }
}
task scheduled
remaining delay: 1
returning result
-7275867025515256187

The methods ScheduledExecutorService#scheduleAtFixedRate() and ScheduledExecutorService#scheduleWithFixedDelay() repeat the task periodically and both return ScheduledFuture<?>, that means the get() method will always return null for them. These futures, however, can be cancelled based on some condition.

public class ScheduledFuturePeriodicExample {
  public static void main(String[] args) throws ExecutionException, InterruptedException {
      ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
      AtomicLong al = new AtomicLong(0);
      ScheduledFuture<?> scheduleFuture = ses.scheduleAtFixedRate(new Runnable() {
          @Override
          public void run() {
              System.out.println("running");
              al.incrementAndGet();
          }
      }, 2, 1, TimeUnit.SECONDS);
      System.out.println("task scheduled");
      Thread.sleep(scheduleFuture.getDelay(TimeUnit.MILLISECONDS));
      while (true) {
          //System.out.println(scheduleFuture.isDone()); will always print false
          Thread.sleep(800);
          long l = al.get();
          System.out.println(l);
          if (l >= 5) {
              System.out.println("cancelling");
              scheduleFuture.cancel(true);
              ses.shutdown();
              break;
          }
      }
  }
}
task scheduled
running
1
running
2
running
3
running
4
running
5
cancelling

Example Project

Dependencies and Technologies Used:

  • JDK 11
  • Maven 3.5.4

ScheduledFuture Examples Select All Download
  • java-scheduled-future-interface
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ScheduledFutureExample.java

    See Also