Ad

Monday 30 September 2013

Lenient and Non-lenient modes of Calendar in Java

In the previous post Working with Calendar ,we saw about how the Calendar API can be used to work with dates in Java.Here we will see about the two modes of the Calendar -Lenient and Non Lenient.
Leninet
   By default the Calendar will be in lenient mode.If we give the wide range of values for the Calendar fields(that doesn't fall under its range),the calendar will accept the value.On the subsequent call of the get..() Method,the Calendar will recomputes and the adjust the value to fall under the range.For example if we set the Month Calendar Field(i.e Calendar.MONTH) to February and Day of the Month Field(i.e Calendar.DAY_OF_MONTH) to be out of range as 30,the lenient calendar will recomputes the date as March 2(as there are only 28 days in February).
Non-Lenient
   To make the calendar in non-lenient mode,lenient flag should be made as false using setLenient() method.If the above out of range Calendar fields were set in Non-lenient Calendar,it will throw the exception on call of any get..() method.Exception will be thrown only on call of get..()(and not during the set or add),since the calendar will recomputes the value only at this time.
we can more more understand about this by seeing the example program below

import java.util.Calendar;                                                                                                                        

public class CalendarLenientExample {

public static void main(String[] args) {
CalendarLenientExample calendarExample= new CalendarLenientExample();
calendarExample.testForLenient();
calendarExample.testForNonLenient();
}
 
/*Calendar in Lenient Mode*/
public void testForLenient() {
Calendar calendar= Calendar.getInstance();//By default the calendar will be in lenient mode
calendar.set(Calendar.MONTH, Calendar.FEBRUARY);
calendar.set(Calendar.DAY_OF_MONTH, 30);
System.out.println("Constructed Date in Lenient Mode:"+calendar.getTime());

}

/*Calendar in Non-Lenient Mode*/
public void testForNonLenient() {
try
{
Calendar calendar= Calendar.getInstance();
calendar.setLenient(false);//Make the Calendar Mode as non-lenient
calendar.set(Calendar.MONTH, Calendar.FEBRUARY);
calendar.set(Calendar.DAY_OF_MONTH, 30);
System.out.println("Constructed Date in NonLenient Mode:"+calendar.getTime());
}
catch(Exception e)
{
System.out.println("Exception encountered in Non-Leneient Mode");
e.printStackTrace();
}
}
}

OUTPUT:
Constructed Date in Lenient Mode:Sat Mar 02 11:23:38 IST 2013
Exception encountered in Non-Leneient Mode
java.lang.IllegalArgumentException: MONTH
at java.util.GregorianCalendar.computeTime(Unknown Source)
at java.util.Calendar.updateTime(Unknown Source)
at java.util.Calendar.getTimeInMillis(Unknown Source)
at java.util.Calendar.getTime(Unknown Source)
at CalendarLenientExample.testForNonLenient(CalendarLenientExample.java:28)
at CalendarLenientExample.main(CalendarLenientExample.java:8)

As we can see in the output,
  •  Although we have given the Calendar.DAY_OF_MONTH to be out of range i.e 30,the getTime() method of the lenient calendar recomputed the value to March 2.
  • In Non-Lenient Mode,the getTime() method of the Calendar thrown the IllegalArgumentException.The exception will also tell as which calendar field was given out of range.In our case it is MONTH as we can see in the exceptionstacktrace. 

Sunday 29 September 2013

Working with Calendar in Java - Using set and add methods

Calendar is an very important API for working and manipulating with dates.we may have the scenario where we need to schedule the job at the specified date/time.So first we may need to construct the specified date object and then schedule using Timer or any other Scheduler Service at the given date.Calendar makes the date construction very easy.It provides the below methods to achieve this.
getInstance()
This static method of the Calendar class return the calendar object with the current date and time.
add(int field,int value)
Will add the given value to the Calendar field for the date in Calendar.There are may Calendar field like Calendar.YEAR,Calendar.MONTH,Calendar.Date,Calendar.HOUR etc.For instance
  • add(Calendar.YEAR,1) - will add 1 year to the date in Calendar
  • add(Calendar.MONTH,1) - will add 1 month to the date in Calendar
  • add(Calendar.DATE,1) - will add 1 day to the date in Calendar
set(int field,int value)
Will set the give value to the Calendar Field for the date in Calendar.For instance
  • set( Calendar.MONTH,Calendar.JANUARY) - will set the month of the calendar to January.
  • set( Calendar.HOUR_OF_DAY,1) - will set the hour part of the time in Calendar as 1.
geTime()
Will return the Java.util.Date object set in the Calendar

we can more understand about this by seeing the sample program below.Lets imagine we need :
1)To construct the date which falls in Next New Year
2)To construct the date which falls in immediate Thursday
3)To construct the date which falls in First Monday of March Month
The program for this is shown below:

import java.util.Calendar;                                                                                                                  

public class CalendarExample {

public static void main(String[] args) {
CalendarExample calendarExample= new CalendarExample();
calendarExample.nextNewYear();
calendarExample.immediateThursday();
calendarExample.firstMondayOfMarch();
}

/*To construct the date which falls in Next New Year*/
public void nextNewYear()
{
Calendar calendar= Calendar.getInstance();
System.out.println("Present Date/Time:"+calendar.getTime());
calendar.add(Calendar.YEAR,1);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
System.out.println("Next Newyear is at:"+calendar.getTime());
}

/*To construct the date which falls in immediate Thursday*/
        public void immediateThursday() {
           Calendar calendar= Calendar.getInstance();
System.out.println("Present Date/Time:"+calendar.getTime());
if(calendar.get(Calendar.DAY_OF_WEEK)>=Calendar.THURSDAY)
{
calendar.add(Calendar.DATE,7);
}
calendar.set(Calendar.DAY_OF_WEEK,Calendar.THURSDAY);
System.out.println("Immediate Thursday is at:"+calendar.getTime());
}
 
        /*To construct the date which falls in First Monday of March Month*/
        public void firstMondayOfMarch() {
           Calendar calendar= Calendar.getInstance();
                System.out.println("Present Date/Time:"+calendar.getTime());
calendar.set(Calendar.MONTH, Calendar.MARCH);
calendar.set(Calendar.DAY_OF_MONTH,1 );
if(calendar.get(Calendar.DAY_OF_WEEK)>Calendar.MONDAY)
{
calendar.set(Calendar.WEEK_OF_MONTH,2);
}
else
{
calendar.set(Calendar.WEEK_OF_MONTH,1);
}
calendar.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND,0);
System.out.println("First Monday of March is at:"+calendar.getTime());
}
}

To construct the date which falls in Next New Year
As we can see in the method nextNewYear(),we got the calendar Instance which will have the current
date and Time.Then we
   1) added 1 year to the calendar using calendar Field Calendar.Year in add method
   2)set the Month as January
   3)Set the Day_OF_THE_MONTH as 1
   4)Set the HOUR_OF_DAY,MINUTE and SECONDS as 0.
If the current year is 2013, Constructed date object will contain value 01/01/2014 00:00:00

To construct the date which falls in immediate Thursday
As we can see in the method immediateThursday() ,we got the calendar Instance which will have the
current date and Time.Then we
   1)First checked if the current day of the week is passed Thursday i.e current day is after Thursday.
   2)If the current day is equal to or after thursday,we added 7 days to the current date.Since thursday is
   passed in current week,we moved to next week.
   3)Then we set the day of the week as Thursday.
If the current date is 29/09/2013 17:52:54, Constructed date object will contain value 03/10/2013 17:52:54

To construct the date which falls in First Monday of March Month
As we can see in the method firstMondayOfMarch() ,we got the calendar Instance which will have the
current date and Time.Then we
   1)Set the Month as March
   2)Set the Day of the Month as 1.
   3)Then we checked if the the First day of the Month has passed Monday i.e to find if the first
   occurrence of  Monday falls is in first Week of March.If the first occurrence of Monday falls in first
   week of March we set the Week_of_month as 1 else set it as 2.
   4)Set the Day_Of_The_week as Monday
   5)Set the HOUR_OF_DAY,MINUTE and SECONDS as 0.
If the current year is 2013, Constructed date object will contain value 04/03/2013 00:00:00

If you run the above program,you will get the output as shown below:

Present Date/Time:Sun Sep 29 17:52:54 IST 2013
Next Newyear is at:Wed Jan 01 00:00:00 IST 2014
Present Date/Time:Sun Sep 29 17:52:54 IST 2013
Immediate Thursday is at:Thu Oct 03 17:52:54 IST 2013
Present Date/Time:Sun Sep 29 17:52:54 IST 2013
First Monday of March is at:Mon Mar 04 00:00:00 IST 2013

Saturday 28 September 2013

Producer and Consumer threads example for use of Synchronization and wait/notify/notifyAll in java multithreading

In this post,we will see about  importance of synchronization in java multithreading  and how wait,notify and notifyAll methods can be used in thread communication

Why we need to go for Synchronization?
    When more than one thread access the shared object,the state of the shared object won't be consistent across the thread.To fix this we have to make only one thread access/modify the shared object at any time , so that its state or value will be consistent across the threads that access it.How we can achieve this?The answer is Synchronization.If we make the method or any block as synchronized,the thread which first enters the method or block will get the object lock for  the object which is synchronized.If any other thread try to enter the synchronized block for the same object,it has to wait until the former thread releases the object lock of the same object.The thread  will releases the object lock either when it completes and leaves the synchronized block/method or the current executing thread call the wait method on the object which it was synchronized.

wait ,notify and notifyAll Method:
These methods are available in java.lang.Object and plays a  very vital role in communication between threads.
wait:
If we call the wait method,the current executing thread will release the object lock of the object(on which the wait method was called) and will go to sleeping state(will wait until it get any notification).
notify:
The notify method call on the object will make the thread which is waiting for the object lock for the object(on which notify was called) to resume its execution as soon as the object lock was avilable.
notifyAll:
notifyAll method will notify all the threads which are waiting for the object lock whereas notify will notify only a single thread.

The wait,notify and notifyAll method should be called only in synchronization context,since the thread can acquire the object lock only if it enters synchronization block or method.Lets understand this with a sample program- Producer and Consumer threads.we have two threads producer and consumer Thread which shares an object queue which is an list of items.The role of producer is to add the item to queue and to notify the consumer about the newly added item.The consumer will take the item from queue and further process it.These two threads should not access the shared object queue at the same time.


import java.util.ArrayList;
import java.util.List;

public class ThreadWaitNotifyExample {

public static void main(String[] args) {
List<String> queue= new ArrayList<String>();
/*Construct and start the Consumer Thread*/
ConsumerThread consumer= new ConsumerThread(queue);
Thread consumerThread=new Thread(consumer,"Consumer Thread");
consumerThread.start();
/*Construct and start the Producer Thread*/
ProducerThread producer= new ProducerThread(queue);
Thread producerThread=new Thread(producer,"Producer Thread");
producerThread.start();

}
}

/*Class For Producer Thread*/
class ProducerThread implements Runnable
{
private List<String> queue=null;
 
public ProducerThread(List<String> queue)
{
this.queue=queue;
}

@Override
public void run() {
int i=0;
String threadName=Thread.currentThread().getName();
while(true)
{
i++;
synchronized (queue) {
    System.out.println(threadName+":Got the queue Object lock");
System.out.println(threadName+":Adding the Item to Queue:Item"+i);
queue.add("Item"+i);
System.out.println(threadName+":Abt to Notify the Consumer for the new Item");
queue.notifyAll();
    System.out.println(threadName+":Releases the queue Object lock");
}
if(i==2)
break;
}
}

}

/*Class For Consumer Thread*/
class ConsumerThread implements Runnable
{
private List<String> queue=null;
public ConsumerThread(List<String> queue)
{
this.queue=queue;
}
@Override
public void run(){
String threadName=Thread.currentThread().getName();
synchronized (queue)
{
 while(true) {
if(queue.size()==0)
{
try {
System.out.println(threadName+":Going to Wait state,Since the Queue is empty");                              
      System.out.println(threadName+":Releases the queue Object lock");
queue.wait();
System.out.println(threadName+":resumed and got the queue object lock");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String item=queue.remove(0);
System.out.println(threadName+":Got the Item from Queue:"+item);
}
}
}
}

synchronized (queue) - The thread which first enter this synchronized block will acquire the object lock of the queue object,so that any other thread tries to get the object lock of the queue(by entering the the synchronized block of the queue) has to wait until the former thread releases the same.Thus at any point of  time both producer and  consumer Thread will not access the queue object at the same time.The detailed program flow is described below:

  • The consumer thread first acquires the object lock of the queue by entering the synchronized block.
  • The producer thread cannot acquire the lock and hence cannot enter the synchronized block.
  • Since the initial queue size is 0,consumer thread goes to wait state by calling the wait method on the queue object and the object lock of the queue will be released.
  • The producer thread will now acquire the object lock by entering the synchronized block and add an item to the queue.Then it will notify all the threads that are waiting for the queue object lock by calling notifyAll on the queue object.
  • Once the producer thread leaves the Synchronized block(object lock will be released),the notified consumer thread will resume and get the added item from queue and process it.
  • Once the queue size becomes zero,consumer thread will again release queue object lock by calling the wait method on queue object.
  • As soon as queue object lock is released,the producer thread will acquire it(by entering the synchronized block) and add an item to queue and notifies the thread waiting for the queue object lock.So this process of adding and retrieval  continues.                                                                     
When you run the above program ,you will get the output as shown below:

Consumer Thread:Going to Wait state,Since the Queue is empty
Consumer Thread:Releases the queue Object lock
Producer Thread:Got the queue Object lock
Producer Thread:Adding the Item to Queue:Item1
Producer Thread:Abt to Notify the Consumer for the new Item
Producer Thread:Releases the queue Object lock
Consumer Thread:resumed and got the queue object lock
Consumer Thread:Got the Item from Queue:Item1
Consumer Thread:Going to Wait state,Since the Queue is empty
Consumer Thread:Releases the queue Object lock
Producer Thread:Got the queue Object lock
Producer Thread:Adding the Item to Queue:Item2
Producer Thread:Abt to Notify the Consumer for the new Item
Producer Thread:Releases the queue Object lock
Consumer Thread:resumed and got the queue object lock
Consumer Thread:Got the Item from Queue:Item2
Consumer Thread:Going to Wait state,Since the Queue is empty
Consumer Thread:Releases the queue Object lock

  

Tuesday 10 September 2013

To find the Asymmetric difference and intersection between two sets in Java using removeAll and retainAll

Set is a collection which is used to hold distinct elements i.e it doesn't allow duplicates.Set
provides two important methods retainAll and removeAll which is used to perform bulk operation like
set-algebric operations.Lets say we have two sets set1 and set2.

set1.retainall(set2)
   This will transform the set1 to hold elements which is present in both set1 and set2.Thus it will give the intersection of the two sets.

set1.removeall(set2)
   This will transform the set1 to hold elements which is present only in set1 and not in set2.Thus it will give the asymmetric difference between this two sets.  

Lets see a sample program below to understand this methods.Let us consider we have two sets,one contains the employees who have Java skill and the other contains employees who have J2ee skill.Our requirement is to:
  • Find the employees who have only Java Skill - use removeAll.
  • Find the employees who have both Java and J2ee Skill - use retainAll.
  • Find the employees who have only J2ee Skill - use removeAll.
import java.util.HashSet;
import java.util.Set;

public class SetExample {

 public static void main(String[] args) {
  Set<String> javaSkillEmpSet = getJavaSkillEmpSet();
  Set<String> j2eeSkillEmpSet = getJ2eeSkillEmpSet();
  javaSkillEmpSet.removeAll(j2eeSkillEmpSet);
  /*javaSkillEmpSet will contain employees who have only Java Skill and not having J2ee Skill*/ 
  System.out.println("Employees who have Only Java skill:"+ javaSkillEmpSet);                                                                    
  javaSkillEmpSet = getJavaSkillEmpSet();
  javaSkillEmpSet.retainAll(j2eeSkillEmpSet);
  /*javaSkillEmpSet will contain employees who have both Java  and  J2ee Skill*/ 
  System.out.println("Employees who have both Java and J2ee skill:"+ javaSkillEmpSet);

  javaSkillEmpSet = getJavaSkillEmpSet();
  j2eeSkillEmpSet.removeAll(javaSkillEmpSet);
  /*j2eeSkillEmpSet will contain employees who have only J2ee Skill and not having Java Skill*/
  System.out.println("Employees who have only J2ee skill:"+j2eeSkillEmpSet);
 }

 /**
  * This Method Will return the Set which contains employees who have Java Skill
  */
 public static Set<String> getJavaSkillEmpSet() {
  Set<String> javaSkillEmpSet = new HashSet<String>();
  javaSkillEmpSet.add("EmpId01");
  javaSkillEmpSet.add("EmpId02");
  javaSkillEmpSet.add("EmpId03");
  javaSkillEmpSet.add("EmpId04");
  return javaSkillEmpSet;
 }

 /**
  * This Method Will return the Set which contains employees who have J2ee Skill
  */
 public static Set<String> getJ2eeSkillEmpSet() {
  Set<String> j2eeSkillEmpSet = new HashSet<String>();
  j2eeSkillEmpSet.add("EmpId01");
  j2eeSkillEmpSet.add("EmpId05");
  j2eeSkillEmpSet.add("EmpId03");
  j2eeSkillEmpSet.add("EmpId06");
  return j2eeSkillEmpSet;
 }
}

Output:
Employees who have Only Java skill:[EmpId02, EmpId04]
Employees who have both Java and J2ee skill:[EmpId01, EmpId03]
Employees who have only J2ee skill:[EmpId06, EmpId05]

Wednesday 4 September 2013

Queuing strategies for ThreadPoolExecutor in Java

In ThreadPoolExecutor queues are used to hold the submitted task, if there are no ideal threads to
run/allocate the task.There are three strategies for the Queuing.
  • Direct Handoffs
  • Unbounded Queues
  • Bounded Queues
we will use the same program written  in the post ThreadPoolexecutor in Java and we will change only the method  createThreadPool() to implement one of the Queuing strategy.Depending on the Queue we use in the ThreadPoolexecutor,the behavior of the threadpool will vary as described in the below sections.

Direct Handoffs:
   In this queuing strategy the queue will not hold any submitted task   and it will always create the threads upto maxpoolsize when there are no ideal threads(CorePoolSize threads are busy) in the Threadpool. Once the maxpoolsize threads also becomes busy,submission of new task will be rejected and can be handled via Rejection Handler.SynchronousQueue can be used for the Direct Handoffs.when the maxpoolsize is defined as more and the time consuming task is arriving faster,there is a possibility more number of threads will be running in the pool.

private void createThreadPool() {                                                                                                            
int poolSize=2;
int maxPoolSize=5;
long aliveTive=1000;
SynchronousQueue<Runnable> queue= new SynchronousQueue<Runnable>();
threadPoolExecutor= new ThreadPoolExecutor(poolSize,maxPoolSize,aliveTive,
               TimeUnit.MILLISECONDS,queue,new JobRejectionHandler());
}

Output for Direct Handoffs:
JobId:Job6 Running through RejectionHandler,Since there is no ideal threads in ThreadPool
JobId:Job7 Running through RejectionHandler,Since there is no ideal threads in ThreadPool
JobId:Job8 Running through RejectionHandler,Since there is no ideal threads in ThreadPool
JobId:Job9 Running through RejectionHandler,Since there is no ideal threads in ThreadPool
JobId:Job10 Running through RejectionHandler,Since there is no ideal threads in ThreadPool
JobId:Job1 Running through Thread:pool-1-thread-1
JobId:Job2 Running through Thread:pool-1-thread-2
JobId:Job3 Running through Thread:pool-1-thread-3
JobId:Job4 Running through Thread:pool-1-thread-4
JobId:Job5 Running through Thread:pool-1-thread-5

As we can see in the above output.
  • Thread-1 and Thread-2 were allocated to run the Task Job1 and Job2.So the corepoolsize threads(i.e 2) are busy in running this task.
  • Once the Job3 is submitted,it is not queued as we used the Direct Handoff.It therefore constructs the thread-4.The same apply for Job4 and Job5 as well which were run by Thread-4 and Thread-5.
  • Since there were no ideal threads in ThreadPool(Since the maxpoolsize is 5 and all 5 threads were busy),submission of task Job6 to Job10 were rejected and were run by the Rejectionhandler. 

Unbounded Queues:
  In this queuing strategy the submitted task will wait in the queue if the corePoolsize theads are busy and the task will be allocated if any of the threads become idle.Thus ThreadPool will always have number of threads running  as mentioned in the corePoolSize.Thus the maxPoolSize will not have any effect in threadpool size. LinkedBlockingQueue without the capacity can be used for this queuing strategy.If the corePoolsize of the threadpool is less and there are more number of time consuming task were submitted,there is more possibility that the task has to wait in the queue for more time before it is run by any of the ideal thread.Also no task will be rejected in Threadpool until the threadpool was shutdown.

private void createThreadPool() {                                                                                                            
int poolSize=2;
int maxPoolSize=5;
long aliveTive=1000;
LinkedBlockingQueue<Runnable> queue= new LinkedBlockingQueue<Runnable>();
threadPoolExecutor= new ThreadPoolExecutor(poolSize,maxPoolSize,aliveTive,
               TimeUnit.MILLISECONDS,queue,new JobRejectionHandler());
}


Output for unbounded Queues:
JobId:Job1 Running through Thread:pool-1-thread-1
JobId:Job2 Running through Thread:pool-1-thread-2
JobId:Job3 Running through Thread:pool-1-thread-1
JobId:Job4 Running through Thread:pool-1-thread-2
JobId:Job5 Running through Thread:pool-1-thread-1
JobId:Job6 Running through Thread:pool-1-thread-2
JobId:Job7 Running through Thread:pool-1-thread-1
JobId:Job8 Running through Thread:pool-1-thread-2
JobId:Job9 Running through Thread:pool-1-thread-1
JobId:Job10 Running through Thread:pool-1-thread-2

As we can see in the above output,
  • Thread-1  and Thread-2 were allocated to run the Task Job1 and Job2. So the corepoolsize threads(i.e 2) are busy in running this task.
  • The forthcoming submitted task job3,Job4 etc will wait in the queue.It will be run by either Thread 1 or Thread 2 when they become idle.
  • Thus only 2 threads will run in the threadpool and the maxPoolsize which was defined as 5 will not have any effect to the threadPool size.  

Bounded Queues:
 We already used this queuing strategy in the example written in post ThreadPoolexecutor in Java .The submitted task will wait in the queue if there are no ideal corepoolsize threads.Once the queue is full,the threads will be created upto maxpoolsize for every submitted task.ArrayBlockingQueue can be used for this queuing strategy.

private void createThreadPool() {                                                                                                            
int poolSize=2;
int maxPoolSize=5;
  int queueSize=3;
long aliveTive=1000;
ArrayBlockingQueue<Runnable> queue= new ArrayBlockingQueue<Runnable>(queueSize);
threadPoolExecutor= new ThreadPoolExecutor(poolSize,maxPoolSize,aliveTive,
               TimeUnit.MILLISECONDS,queue,new JobRejectionHandler());
}

Output for unbounded Queues:
JobId:Job1 Running through Thread:pool-1-thread-1
JobId:Job2 Running through Thread:pool-1-thread-2
JobId:Job9 Running through RejectionHandler,Since there are no ideal threads in ThreadPool
JobId:Job10 Running through RejectionHandler,Since there are no ideal threads in ThreadPool
JobId:Job6 Running through Thread:pool-1-thread-3
JobId:Job7 Running through Thread:pool-1-thread-4
JobId:Job8 Running through Thread:pool-1-thread-5
JobId:Job3 Running through Thread:pool-1-thread-1
JobId:Job4 Running through Thread:pool-1-thread-2
JobId:Job5 Running through Thread:pool-1-thread-3

Related Topics:
ThreadPoolexecutor in Java
Rejected Handler Policies for ThreadPoolExecutor

Friday 30 August 2013

ThreadPoolExecutor - Handler Policies for Rejected Task in Java

In the previous post "ThreadPoolexecutor in Java" we created our user defined RejectedHandler,which will be invoked if any task is rejected by the ThreadPoolExecutor.In addition to defining user defined RejectedHandler,ThreadPoolExecutor provides four predefined handler polices for handling the rejected task:
  1. ThreadPoolExecutor.AbortPolicy
  2. ThreadPoolExecutor.CallerRunsPolicy
  3. ThreadPoolExecutor.DiscardPolicy
  4. ThreadPoolExecutor.DiscardOldestPolicy
If you remember the program used in the post ThreadPoolExecutor in Java we created the ThreadPool in the method createThreadPool and the user defined Rejected Handler was used in the 
ThreadPool as shown below:

private void createThreadPool() {
  int poolSize=2;
  int maxPoolSize=5;
  int queueSize=3;
  long aliveTive=1000;
  ArrayBlockingQueue<Runnable> queue= new ArrayBlockingQueue<Runnable>(queueSize);
  threadPoolExecutor= new ThreadPoolExecutor(poolSize,maxPoolSize,aliveTive,
                    TimeUnit.MILLISECONDS,queue,new JobRejectionHandler());
 }

When we run the program,we will get the below output.The below output shows that the rejected task 
were handled through our defined Rejection Handler  JobRejectionHandler.

Output For User defined Handler:

JobId:Job1 Running through Thread:pool-1-thread-1
JobId:Job2 Running through Thread:pool-1-thread-2
JobId:Job9 Running through RejectionHandler,Since there are no ideal threads in ThreadPool
JobId:Job10 Running through RejectionHandler,Since there are no ideal threads in ThreadPool
JobId:Job6 Running through Thread:pool-1-thread-3
JobId:Job7 Running through Thread:pool-1-thread-4
JobId:Job8 Running through Thread:pool-1-thread-5
JobId:Job3 Running through Thread:pool-1-thread-1
JobId:Job4 Running through Thread:pool-1-thread-2
JobId:Job5 Running through Thread:pool-1-thread-3

We will use the predefined handler policies while creating the ThreadPool in method createThreadPool() and will see how the output varies for each of the rejection policies.

1)ThreadPoolExecutor.AbortPolicy
    By using this handler policy in ThreadPoolExecutor,the handler will throw the exception RejectedExecutionException if any task is rejected by the Threadpool. Change the method createThreadPool() to have the ThreadPoolExecutor.AbortPolicy as the handler policy as shown below and run the program.

private void createThreadPool() {
  int poolSize=2;
  int maxPoolSize=5;
  int queueSize=3;
  long aliveTive=1000;
  ArrayBlockingQueue<Runnable> queue= new ArrayBlockingQueue<Runnable>(queueSize);
  threadPoolExecutor= new ThreadPoolExecutor(poolSize,maxPoolSize,aliveTive,
                TimeUnit.MILLISECONDS,queue,new ThreadPoolExecutor.AbortPolicy());
 }

Output for AbortPolicy:

JobId:Job1 Running through Thread:pool-1-thread-1
JobId:Job2 Running through Thread:pool-1-thread-2
JobId:Job6 Running through Thread:pool-1-thread-3
JobId:Job7 Running through Thread:pool-1-thread-4
Exception in thread "main" java.util.concurrent.RejectedExecutionException
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.reject(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.execute(Unknown Source)
at ThreadPoolExample.submitTask(ThreadPoolExample.java:43)
at ThreadPoolExample.main(ThreadPoolExample.java:19)
JobId:Job8 Running through Thread:pool-1-thread-5
JobId:Job3 Running through Thread:pool-1-thread-1
JobId:Job4 Running through Thread:pool-1-thread-2
JobId:Job5 Running through Thread:pool-1-thread-3

As we can see in the above output the task Job9 and Job10 were rejected by the ThreadPool and hence 
the RejectedExecutionException was thrown.

2)ThreadPoolExecutor.CallerRunsPolicy
     By using this handler policy in ThreadPool,the handler will invoke the rejected task in the thread which called the execute method i.e the Caller which added this task to the ThreadPool. Change the method createThreadPool() to have the ThreadPoolExecutor.CallerRunsPolicy as the handler policy and 
run the program.This handler will slowdown the task addition to the ThreadPool if there is any rejected task since the caller(which adds the task to ThreadPool) will run the rejected task.

private void createThreadPool() {
  int poolSize=2;
  int maxPoolSize=5;
  int queueSize=3;
  long aliveTive=1000;
  ArrayBlockingQueue<Runnable> queue= new ArrayBlockingQueue<Runnable>(queueSize);
  threadPoolExecutor= new ThreadPoolExecutor(poolSize,maxPoolSize,aliveTive,
                TimeUnit.MILLISECONDS,queue,new ThreadPoolExecutor.CallerRunsPolicy())
 }

Output for CallerRunsPolicy:

JobId:Job1 Running through Thread:pool-1-thread-1
JobId:Job2 Running through Thread:pool-1-thread-2
JobId:Job9 Running through Thread:main
JobId:Job6 Running through Thread:pool-1-thread-3
JobId:Job7 Running through Thread:pool-1-thread-4
JobId:Job8 Running through Thread:pool-1-thread-5
JobId:Job3 Running through Thread:pool-1-thread-1
JobId:Job4 Running through Thread:pool-1-thread-2
JobId:Job5 Running through Thread:pool-1-thread-3
JobId:Job10 Running through Thread:pool-1-thread-4

As we can see in the above output the task Job9  were rejected by the ThreadPool and the handler ran 
it through the Main thread since the Main Thread is the one which added the task to the ThreadPool. Also we can notice that the task Job10 was not rejected by the ThreadPool. It is due to the slowness in adding the task to the ThreadPool,since the caller i.e Main Thread has run the rejected task Job 9 and by the time Job10 was added ,an ideal thread in the pool was found to  run the task.

3)ThreadPoolExecutor.DiscardPolicy
    This  handler will silently discards the rejected task and will not take any action for the rejected task.Change the method createThreadPool() to have the ThreadPoolExecutor.DiscardPolicy as the handler policy and run the program.

private void createThreadPool() {
  int poolSize=2;
  int maxPoolSize=5;
  int queueSize=3;
  long aliveTive=1000;
  ArrayBlockingQueue<Runnable> queue= new ArrayBlockingQueue<Runnable>(queueSize);
  threadPoolExecutor= new ThreadPoolExecutor(poolSize,maxPoolSize,aliveTive,
                TimeUnit.MILLISECONDS,queue,new ThreadPoolExecutor.DiscardPolicy());
 }

Output for DiscardPolicy:

JobId:Job1 Running through Thread:pool-1-thread-1
JobId:Job2 Running through Thread:pool-1-thread-2
JobId:Job6 Running through Thread:pool-1-thread-3
JobId:Job7 Running through Thread:pool-1-thread-4
JobId:Job8 Running through Thread:pool-1-thread-5
JobId:Job3 Running through Thread:pool-1-thread-1
JobId:Job4 Running through Thread:pool-1-thread-2
JobId:Job5 Running through Thread:pool-1-thread-3

As we can see in the above output the rejected task Job9 and Job10 were silently discarded by the handler and were no action taken by the handler.

4)ThreadPoolExecutor.DiscardOldestPolicy
    If any added task is about to be rejected,the handler will discards the oldest unallocated task until it finds the ideal thread and then  execute the current task through the ideal thread.Change the method createThreadPool() to have the ThreadPoolExecutor.DiscardOldestPolicy as the handler policy and run the program.

private void createThreadPool() {
  int poolSize=2;
  int maxPoolSize=5;
  int queueSize=3;
  long aliveTive=1000;
  ArrayBlockingQueue<Runnable> queue= new ArrayBlockingQueue<Runnable>(queueSize);
  threadPoolExecutor= new ThreadPoolExecutor(poolSize,maxPoolSize,aliveTive,
                TimeUnit.MILLISECONDS,queue,new ThreadPoolExecutor.DiscardOldestPolicy());
 }

Output for DiscardOldestPolicy:

JobId:Job1 Running through Thread:pool-1-thread-1
JobId:Job2 Running through Thread:pool-1-thread-2
JobId:Job6 Running through Thread:pool-1-thread-3
JobId:Job7 Running through Thread:pool-1-thread-4
JobId:Job8 Running through Thread:pool-1-thread-5
JobId:Job5 Running through Thread:pool-1-thread-1
JobId:Job9 Running through Thread:pool-1-thread-2
JobId:Job10 Running through Thread:pool-1-thread-3

As we can see in the above output,the ThreadPool discard the task Job 3 and Job 4.This due to:
  • Since there were no ideal threads to run the task Job9 and hence the task will handled by the handler.
  • The handler then discards the oldest unallocated task which is task Job3 waiting in the queue. Then an  ideal thread in the poolwas found to run the task Job9.
  • The same apply for Job 10 as well which made the handler to discard the oldest task Job4 and then an ideal thread was found to run the task Job10.
Related Topics:

Saturday 24 August 2013

ThreadPoolExecutor-To write ThreadPool in Java


ThreadPoolExecutor is an implementation of ExecutorService which is used to maintain  ThreadPool for allocating and running  Threads.If we don't go for ThreadPool we wont have the control over the  no of Threads created and which will consume more system Resouces.
By using the ThreadPool we can achieve
  • Will create only the configured number of Threads
  • Will reuse the existing ideal Thread to run the Task
  • Will improve the performance and manages the System Resources well.   
So if your requirement is to run many asynchronous Task(i.e Thread),go for the ThreadPoolExecutor which manages the asynchronous task by consuming less system resources.
ThreadPoolExecutor can be created using one of its constructor as shown below

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,        
BlockingQueue<Runnable> workQueue, RejetedExecutionHandler handler)

corePoolSize

  -Minimum Number of Threads in the Pool
maxPoolSize - Maximum Number of Threads in the Pool
keepAliveTime - If the number of running threads is more than CorePoolSize,the ideal Threads will wait  for keep alivetime before terminating
unit - Timeunit for the keepAliveTime i.e MilliSeconds,Seconds or Minutes
workQueue - the queue which is used to hold any new task submitted,if the corePoolSize threads are     busy
handler - The handler to be executed,if any of the submitted task is rejected by the                  ThreadPoolExecutor

For instance lets says we create the ThreadPoolExecutor with corePoolSize as 2,queuesize as 3,maxPoolSize as 5 and keepalivetime as 1 seconds.To start with for each submitted task,Thread will be created upto corePoolSize(i.e 2) and the task will be handled.If this two threads are busy in doing some work and if a new task is submitted the task will be queueud up in the Blocking queue instead of creating a thread.If still the 2 threads are busy and  the blockingQueue is full(i.e 3),the threads  will be created upto maxpoolsize(i.e 5)  in the pool for every submitted task.If  the queue is full and still the 5 threads created (i.e maxPoolSize) are busy,for any new submitted task the task will be rejected and handled through the RejectedExecutionHandler.If  no. of threads running is more than corePoolSize and any thread is idle for 1 seconds the thread will be terminated and only the corePoolSize(i.e 2) thread will be running in pool.Thus at any time the size of the Threadpool will be between corePoolSize(ie 2) and maxPoolSize(ie 5).

To add a task to the ThreadPool,we need to use the below method of ThreadPoolExecutor

public void execute(Runnable Task)                                                                                                     

Lets see a sample code to illustate this.

import java.util.TimerTask;                                                                                                                  
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExample {

 private ThreadPoolExecutor threadPoolExecutor=null;

 public static void main(String[] args) {
  ThreadPoolExample threadPoolExample= new ThreadPoolExample();
  threadPoolExample.createThreadPool();//To create the ThreadPool
  threadPoolExample.submitTask();//To submit the Task
 }

 private void createThreadPool() {
  int poolSize=2;
  int maxPoolSize=5;
  int queueSize=3;
  long aliveTive=1000;
  ArrayBlockingQueue<Runnable> queue= new ArrayBlockingQueue<Runnable>(queueSize);
  threadPoolExecutor= new ThreadPoolExecutor(poolSize,maxPoolSize,aliveTive,
                    TimeUnit.MILLISECONDS,queue,new JobRejectionHandler());
 }

 private void submitTask()
 {
  /*Submit 10 AsunchronousTask to ThreadPool */
  for (int i=1;i<=10;i++)
  {
   threadPoolExecutor.execute(new JobTask("Job"+i));
  }
 }

 /*Asyncchrounous Task Should extend TimerTask*/
 class JobTask extends TimerTask
 {
  private String jobId="";

  public JobTask(String jobId)
  {
   this.jobId=jobId;
  }

  public String getJobId() {
   return jobId;
  }

  @Override
  public void run() {
 
   System.out.println("JobId:"+jobId+" Running through Thread:"+Thread.currentThread().getName());
   /*Make the Task to sleep for 5 seconds,so that the task will be busy*/
   try {
    Thread.sleep(5*1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
    }

/*RejectionHandler to handle any rejected Task*/
 class JobRejectionHandler implements RejectedExecutionHandler
 {

  @Override
  public void rejectedExecution(Runnable arg0, ThreadPoolExecutor arg1) {
   JobTask jobTask=(JobTask)arg0;
      System.out.println("JobId:"+jobTask.getJobId()+" Running through RejectionHandler,Since "
                   +"there are no ideal threads in ThreadPool");
  }

 }
}

Output:

JobId:Job1 Running through Thread:pool-1-thread-1
JobId:Job2 Running through Thread:pool-1-thread-2
JobId:Job9 Running through RejectionHandler,Since there are no ideal threads in ThreadPool
JobId:Job10 Running through RejectionHandler,Since there are no ideal threads in ThreadPool
JobId:Job6 Running through Thread:pool-1-thread-3
JobId:Job7 Running through Thread:pool-1-thread-4
JobId:Job8 Running through Thread:pool-1-thread-5
JobId:Job3 Running through Thread:pool-1-thread-1
JobId:Job4 Running through Thread:pool-1-thread-2
JobId:Job5 Running through Thread:pool-1-thread-3

As we can see in the above output,
  • ThreadPoolExecutor allocates Thread-1 and Thread-2 to handle task Job1 and Job2
  • Since these two threads were busy and the poolsize exceeds two(ie corePoolSize),the newly submitted task Job3,Job4 and Job5 were queued up in the BlockngQueue.
  • Since the queueSize also exceeds(i.e 3),ThreadPool creates three threads(Since maxpoolsize is 5 and already two threads were running)to handle task Job6,Job7 and Job8
  • Since the queue is also full and  the number of threads already allocated exceeds 5(i.e maxpoolsize),the submitted task Job9 and Job10 will be rejected by the ThreadPool and the corresponding rejected handler will be called
  • When any of the 5 running threads become idle,Thread pool will allocate the ideal thread to the task which are added in the Queue.Thus Job3,4 and 5 were allocated to Thread 1,2 and 3 as seen in the output.
  • when there are no task to be run and the thread become idle,the corresponding thread will be terminated i.e Thread 3,4 and 5 will be terminated after they become idle for 1 second.
  • Only two Threads Thread-1 and Thread-2 will running in the ThreadPool waiting for any incoming task.   
Related Topics :

Wednesday 21 August 2013

Servlet Life Cycle - Callback Methods

When we start the app/webserver ,the webscontainer will be loaded.Then the webcontainer will
loads the servlet and it is responsible for maintaining the servlet life cycle by calling the Servlet call back methods.The three callback methods servlet provides to the webcontainer are
  1. init()
  2. Service()
  3. destroy()

1.init()
 This method will be called only once by the webcontainer during service life cycle.Init method
provides us to write any initialization code for the servlet like creating the database connection,socket connections or loading any objects etc.Init method will be called by the container either at

  •    For the servlets which are declared as <load-on-start-up> in web.xml,Init method will be called on      Server starup.Thus the Servlet will be initiatized during the server startup.
  •    For the servlets which are not declared as <load-on-startup> in web.xml,Init method will be called      on handling the first request for the servlet.Thus the servlet will be initiatizied only this time.On          handling the Subsequent request,Init method wont be invoked.


2.Service()
Once the servlet is initialized(ie init() method is invoked),servlet is ready to handle client requests.On receiving the request for the Servlet,the container will invoke the Service method.Depending on the Value of the Http Method in the  request(ie GET/POST),doGet() or doPost()
method will be invoked from the service method.

3.destroy()
When the Servlet is about to be destroyed,Container will call the destroy() call back method of the servlet.It provides us to write any clean up code like cleaning up the database connection,socket connection etc.As we expect this destroy call back  method will be invoked on shutting down the
server.

Friday 9 August 2013

Task already scheduled or cancelled - Exception in Timer and Timer Task

While working with Timer and TimerTask,Sometime we will get the below Exception

Exception in thread "main" java.lang.IllegalStateException: Task already scheduled or cancelled
at java.util.Timer.sched(Unknown Source)
at java.util.Timer.schedule(Unknown Source)

The exception may be due to any one of the below scenario
 (1)We would have scheduled the Same Timetask object(same reference) ,which was scheduled alreadyWe  (2)would have scheduled TimerTask on the cancelled Timer
Lets see the below code example to understand this.

(1) Exception due to Scheduling the same Timer Task object reference
Lets imagine our requirement is to schedule a task to run after 15 and 25 seconds.Hence we schedule the task twice as shown below

public class TimerExample {

public static void main(String[] args) {
    TimerExample timerExample= new TimerExample();
    timerExample.timerDemoForException();
   /*Have an infinite while loop,so that Main progran wont be terminated*/ 
   while (true)
    {
   
    }
}

public void timerDemoForException()
{
Timer timer= new Timer();
Clock clock= new Clock();
timer.schedule(clock, 15*1000);//to Schedule the task to run after 15 seconds
timer.schedule(clock, 25*1000);//to Schedule the task to run after 25 seconds
}

class Clock extends TimerTask
{

@Override
public void run() {
System.out.println("Now the Tume is:"+new Date());
}
}

When we run the above program it will throw the exception "java.lang.IllegalStateException: Task already scheduled or cancelled",since we have used the same timer task object reference for scheduling twice.To resolve this,always create new Timer Task object for scheduling the Timer everytime as shown in the below code.

   public void TimerDemoForException()
{
Timer timer= new Timer();
Clock clock= new Clock();
timer.schedule(clock, 5*1000);
   clock= new Clock();//Instantiate the new Task object
timer.schedule(clock, 15*1000);
}

(2) Exception due to Scheduling the  Timer Task on cancelled Timer

For some requirement,we may like to cancel all the Scheduled Task when some condition meet.
Calling the cancel method on the Timer object,will clear all the scheduled task on the Timer object.
Thus all the scheduled task will not run and if we try to schedule any more task on the cancelled timer will throw the exception "java.lang.IllegalStateException: Timer alreadycancelled" .The below code block will show this.

 public void timerDemoForException()
{
Timer timer= new Timer();
Clock clock= new Clock();
timer.schedule(clock, 10*1000);
  timer.cancel();
  clock= new Clock();
timer.schedule(clock, 15*1000);
}

To resolve this,we need to re instantiate the timer object and then the task has to be scheduled like below code.

public void timerDemoForException()
{
Timer timer= new Timer();
Clock clock= new Clock();
timer.schedule(clock, 10*1000);
  timer.cancel();
  timer= new Timer();//Instantiate the new Timer object
  clock= new Clock();
timer.schedule(clock, 15*1000);
}

Related Topics:
Example - Timer and Timertask in Java
TimerTask - Choosing the correct Schedule Method

Thursday 8 August 2013

Timer and TimerTask in Java- An Example

In the last Post,we saw the description about each of the schedule method provided by the Timer API.
Lets start with a sample program to demonstrate how the Timer can can be used to schedule the task.

Let say our task(Job)  is to display the Current Time and need to be scheduled to run at different time.We need to write a Task for this-MyTimerTask and that should extend the Class TimerTask .The implementation(ie displaying the current Time) of the Task  has to be written in the run method.Then the task can be scheduled to run by using any of the schedule method of the Timer API depending on our requirement.

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerExample {

public static void main(String[] args) {

    TimerExample timerExample= new TimerExample();
    timerExample.scheduleTimerTask();
     /*Have an Infinite while loop,so that the main program wont be terminated */
    while (true)
    {
   
    }
}

public  void scheduleTimerTask()
{
Timer timer= new Timer();
MyTimerTask timerTask=null;
Calendar calendar= Calendar.getInstance();
calendar.set(Calendar.HOUR,10);
calendar.set(Calendar.MINUTE,00);
calendar.set(Calendar.SECOND,00);
System.out.println("calendar"+calendar.getTime());

/*To Schedule the task to run once after 5 seconds*/
timerTask= new MyTimerTask("Type1");
timer.schedule(timerTask,5*1000); //

/*To Schedule the task to run once at Current Date 10:00 AM*/
timerTask= new MyTimerTask("Type2");
 timer.schedule(timerTask,calendar.getTime());

  /*Fixed Delay Execution-To Schedule the task to run repeatedly with specified
   interval of 5 seconds.First Time execution of the Task will start after 10 seconds*/
 timerTask= new MyTimerTask("Type3");
timer.schedule(timerTask,10*1000,5*1000);

/*Fixed Delay Execution-To Schedule the task to run repeatedly with specified
interval of 5 seconds.First Time execution of the Task will start at current Date 10:00 AM*/
timerTask= new MyTimerTask("Type4");
timer.schedule(timerTask,calendar.getTime(),5*1000);

/*Fixed Rate Execution-To Schedule the task to run repeatedly with specified
interval of 5 seconds.First Time execution of the Task will start at current Date 10:00 AM*/
timerTask= new MyTimerTask("Type5");
timer.scheduleAtFixedRate(timerTask,calendar.getTime(),5*1000);

/*Fixed Rate Execution-To Schedule the task to run repeatedly with specified
 interval of 5 seconds.First Time execution of the Task will start after 10 seconds*/
timerTask= new MyTimerTask("Type6");
timer.scheduleAtFixedRate(timerTask,10*1000,5*1000);
}

}

class MyTimerTask extends TimerTask
{

private String scheduleType="";
public MyTimerTask(String scheduleType)
{
this.scheduleType=scheduleType;
}

@Override
public void run() {
System.out.println("Job of Scheduled Type:"+scheduleType+" Is executed at Time:"+new Date());
}

}

Related Topics:

Tuesday 30 July 2013

Timer and TimerTask in Java - Choosing the Correct Schedule Method(Schedule and scheduleAtFixedRate)

Timer API provides the ability to
  1. Schedule   the Job/Task to run at the specified time
  2. Schedule the Job/Task to run repeatedly with specified interval of Time
Timer API Provides 6 methods to achieve this.Big Question arise to all is , which method we need
to choose.The selection of the method depends on our requirement matching the  below criteria
  • We need to schedule the task for the  single  execution or repeated execution
  • We need the task to be scheduled at the specified time or to be after the specified delay in milliseconds
  • We need a fixed delay execution or fixed rate execution

Method public void schedule(TimerTask task,long delay)
Description To execute the task after the specified delay in milliseconds.So choose this method,if your requirement is to schedule for the single time execution and to be run after the specified delay

Method public void schedule(TimerTask task, Date time)
Description To execute the task at specified time.So choose this method,if your requirement is to schedule for the single time execution and need to scheduled at the specified time

Method public void schedule(TimerTask task,long delay,long interval)
Description To execute the task repeatedly with specified interval of time.The First execution of the task will start after the specified delay in milliseconds.Each task will run relative to the previous execution time(ie previous task execution time+interval).So use this method,if you requirement is for the repeated execution and need to be a fixed delay execution and also the first execution has to be started after the specified delay

Method public void schedule(TimerTask task,Date firstTime,long interval)
Description To execute the task repeatedly with specified interval of time.The First execution of the task will start at the time(firstTime) specified.Each task will run relative to the previous execution time(ie previous task execution time+interval).So use this method,if you requirement is for the repeated execution and need to be a fixed delay execution and also the first execution has to be started at the specified time

Method scheduleAtFixedRate(TimerTask task, Date firstTime, long interval)
Description To execute the task repeatedly with specified interval of time.The First execution of the task will start at the time(firstTime) specified.Each task will run relative to the initial task execution time(Initial task executiontime + taskcompletedcount*interval).So use this method,if you requirement is for the repeated execution and need to be a fixed rate execution and also the first execution has to be started at the specified time

Method scheduleAtFixedRate(TimerTask task, long delay, long interval)
Description To execute the task repeatedly with specified interval of time.The First execution of the task will start after the specified delay in milliseconds.Each task will run relative to the initial task execution time(Initial task executiontime + taskcompletedcount*interval).So use this method,if you requirement is for the repeated execution and need to be a fixed rate execution and also the first execution has to be started after the specified delay

For the sample program on Timer Task,please refer this Post Timer Task-Example

Related Topics:
Example - Timer and TimerTask
Exception - Task already scheduled or cancelled