Friday, 16 September 2016

Java 5 - ScheduledExecutorService - new way of writing java scheduler

Java Timer/TimerTask was used for scheduling tasks which requires to be executed at certain interval, frequency etc. Java 5 introduced the concept of thread pool for limiting number of threads executing at a particular point of time. Creating a thread consumes a significant amount of memory and hence limiting the number of threads via thread pool will give better performance and saves memory.

Java 5 documentation recommends to use ScheduledExecutorService for creating scheduler jobs. This is further simpler implementation and doesn't require subclassing as was required in case of a TimerTask.

Example scheduler using ScheduledExecutorService is as follows:

package com.prasune.test.concurrent;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class SchedulerService {
    public static void main(String[] args) {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(5);
        Runnable command = new Runnable() {           
            public void run() {
                System.out.println("Executing the scheduler " + new Date());
        // Creates and executes a periodic action that becomes enabled first
        // after the given initial delay, and subsequently with the given period
        final ScheduledFuture timerHandle =
                scheduler.scheduleAtFixedRate(command, 5, 60, TimeUnit.SECONDS);
        // Stop command execution after one hour
        Runnable cancelTimerCommand = new Runnable() {
            public void run() {
        scheduler.schedule(cancelTimerCommand, 60 * 60, TimeUnit.SECONDS);