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