Home » Core Java » util » concurrent » RunnableScheduledFuture » Java RunnableScheduledFuture Example

About Mohammad Meraj Zia

Mohammad Meraj Zia
I did my Engineering in Information Technology from IET, Lucknow, India. Currently doing MSc in Information Technology from Derby University. I have worked in Java/J2EE domain for the last 10 years. Have good understanding of Payment and Finance domains.

Java RunnableScheduledFuture Example

In this article we will learn about java.util.concurrent.RunnableScheduledFuture class which was introduced in Java 6.

1. Introduction

Java RunnableScheduledFuture is a ScheduledFuture that is Runnable. Successful execution of the run method causes completion of the Future and allows access to its results.

public interface RunnableScheduledFuture<V> extends RunnableFuture<V>, ScheduledFuture<V>

To know how RunnableScheduledFuture works first we need to learn about java.util.concurrent.Future.

1.1 java.util.concurrent.Future

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled. If you would like to use a Future for the sake of cancellability but not provide a usable result, you can declare types of the form Future<?> and return null as a result of the underlying task.

1.2 java.util.concurrent.FutureTask

This class was added in java 5.

public class FutureTask<V> extends Object implements RunnableFuture<V>

A FutureTask is a cancellable asynchronous computation. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed. Once the computation has completed, the computation cannot be restarted or cancelled (unless the computation is invoked using runAndReset()).

A FutureTask can be used to wrap a Callable or Runnable object. Because FutureTask implements Runnable, a FutureTask can be submitted to an Executor for execution.

In addition to serving as a standalone class, this class provides protected functionality that may be useful when creating customized task classes.

2. Example

Let us understand this using an example. We will create a simple task which we will schedule to run after 5 seconds. First we will create an instance of ScheduledExecutorService using Executors

ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

ScheduledExecutorService
A ScheduledExecutorService is an ExecutorService that can schedule commands to run after a given delay, or to execute periodically. The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution. The scheduleAtFixedRate and scheduleWithFixedDelay methods create and execute tasks that run periodically until cancelled. Commands submitted using the Executor.execute(Runnable) and ExecutorService submit methods are scheduled with a requested delay of zero.Zero and negative delays (but not periods) are also allowed in schedule methods, and are treated as requests for immediate execution.
All schedule methods accept relative delays and periods as arguments, not absolute times or dates. It is a simple matter to transform an absolute time represented as a java.util.Date to the required form. For example, to schedule at a certain future date, you can use: schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS). Beware however that expiration of a relative delay need not coincide with the current Date at which the task is enabled due to network time synchronization protocols, clock drift, or other factors.
The Executors class provides convenient factory methods for the ScheduledExecutorService implementations provided in this package.

Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:

ScheduledExecutorService.java

import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
  private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  
  public void beepForAnHour() {
    final Runnable beeper = new Runnable() {
      public void run() { System.out.println("beep"); }
    };
    final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
    scheduler.schedule(new Runnable() {
      public void run() { beeperHandle.cancel(true); }
    }, 60 * 60, SECONDS);
  }
}

Executors
Executors class provide factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes defined in this package. This class supports the following kinds of methods:

  • Methods that create and return an ExecutorService set up with commonly useful configuration settings.
  • Methods that create and return a ScheduledExecutorService set up with commonly useful configuration settings.
  • Methods that create and return a “wrapped” ExecutorService, that disables reconfiguration by making implementation-specific methods inaccessible.
  • Methods that create and return a ThreadFactory that sets newly created threads to a known state.
  • Methods that create and return a Callable out of other closure-like forms, so they can be used in execution methods requiring Callable.

The newSingleThreadScheduledExecutor method creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newScheduledThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.
Now we will create a new task. This is a very simple task which waits for 5 seconds then return an int value (in our case it’s 100)

Callable Scheduled Task

Callable scheduledTask = new Callable() {
  public Integer call() {
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return 100;
  }
};

Next we will create a scheduled task by calling the schedule() method of ScheduledExecutorService

Future output = scheduledExecutorService.schedule(scheduledTask, 5, TimeUnit.SECONDS);

Below is the full source code:

ScheduledTaskExample.java

package com.javacodegeeks;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledTaskExample {

    public static void main(String[] args) {
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

        Callable<Integer> scheduledTask = new Callable<Integer>() {
            public Integer call() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return 100;
            }
        };

        Future<Integer> output = scheduledExecutorService.schedule(scheduledTask, 5, TimeUnit.SECONDS);

        try {
            Integer value = output.get();
            System.out.println("### Value is " + value);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        scheduledExecutorService.shutdown();
    }
}

3. Conclusion

In this article we discussed about the Java RunnableScheduledFuture class. We also discussed about it’s usage as well. In the end we looked at a typical example of scheduling a task using Java scheduling framework.

4. Download the Source Code

Download
You can download the full source code of this example here: Scheduled Task
(+2 rating, 2 votes)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of