Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, January 24, 2015

How to make Java Timer to execute tasks concurrently?

What is Java Timer?    Java Timer is used to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.

How are tasks executed by Timer object?    Each timer object has a single background thread that is used to execute all of the timer's tasks, sequentially.

Can Timer execute more than one task at a time?
    The default implementation of Timer will execute the task only in sequential order. For example, if you've scheduled two task at 7 PM and 8 PM respectively. And if the first task takes 5 hours to complete, then the second task will only be executed only after 12'o clock.

How to make Java Timer to execute tasks concurrently?
Solution 1:
    Create multiple timers. Each timer will execute one task at time. If you want to run three tasks subsequently, you need to create three different timer objects.

Solution 2:
    Run all the tasks in a separate Thread. In the example given above, Timer thread will create one worker thread to execute the fist task at 7 PM and second task at 8 PM respectively. 

Sample Code (Solution 2):


import java.util.*;

public class JavaTimer {

public static void main(String[] args) {
Timer timer = new Timer();

timer.schedule(new Task1(), Calendar.getInstance().getTime());
timer.schedule(new Task2(), Calendar.getInstance().getTime());
timer.schedule(new Task3(), Calendar.getInstance().getTime());
}
}

class TaskBase extends TimerTask
{
public String getName()
{
return this.getClass().getName();
}

@Override
public void run() {
                //Creates a new thread for each task.
new Thread() {
public void run() {
runInAnotherThread();
}
}.start();
}

public void runInAnotherThread() {
System.out.println(getName()+" Scheduled Time: "+new Date(this.scheduledExecutionTime()));
System.out.println(getName()+" Executed Time: "+new Date());
doTask();

}

public void doTask()
{
System.out.println("Will be implemented by sub classes");
}
}

class Task1 extends TaskBase
{
public void doTask()
{
System.out.println("DoTask of Task1");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("End of DoTask of Task1");
}
}

class Task2 extends TaskBase
{
public void doTask()
{
System.out.println("DoTask of Task2");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("End of DoTask of Task2");
}
}

class Task3 extends TaskBase
{
public void doTask()
{
System.out.println("DoTask of Task3");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("End of DoTask of Task3");
}

}