Thursday, March 13, 2014

Callable & Future

In last few posts, we learned a lot about java threads but sometimes we wish that a thread could return some value that we can use. Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.
Callable interface use Generic to define the return type of Object. Executors class provide useful methods to execute Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object. Callable tasks return java.util.concurrent.Future object. Using Future we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.
Future provides cancel() method to cancel the associated Callable task. There is an overloaded version of get() method where we can specify the time to wait for the result, it’s useful to avoid current thread getting blocked for longer time. There are isDone() and isCancelled() methods to find out the current status of associated Callable task.
Here is a simple example of Callable task that returns the name of thread executing the task after one second. We are using Executor framework to execute 100 tasks in parallel and use Future to get the result of the submitted tasks.
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MyCallable implements Callable<String> {

    @Override
    public String call() throws Exception {
        Thread.sleep(1000);
        //return the thread name executing this callable task
        return Thread.currentThread().getName();
    }
   
    public static void main(String args[]){
        //Get ExecutorService from Executors utility class, thread pool size is 10
        ExecutorService executor = Executors.newFixedThreadPool(10);
        //create a list to hold the Future object associated with Callable
        List<Future<String>> list = new ArrayList<Future<String>>();
        //Create MyCallable instance
        Callable<String> callable = new MyCallable();
        for(int i=0; i< 100; i++){
            //submit Callable tasks to be executed by thread pool
            Future<String> future = executor.submit(callable);
            //add Future to the list, we can get return value using Future
            list.add(future);
        }
        for(Future<String> fut : list){
            try {
                //print the return value of Future, notice the output delay in console
                // because Future.get() waits for task to get completed
                System.out.println(new Date()+ "::"+fut.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        //shut down the executor service now
        executor.shutdown();
    }

}
Once we execute the above program, you will notice the delay in output because Future get() method waits for the callable task to complete. Also notice that there are only 10 threads executing these tasks.
Here is snippet of the output of above program.
Mon Dec 31 20:40:15 PST 2012::pool-1-thread-1
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-2
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-3
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-4
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-5
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-6
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-7
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-8
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-9
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-10
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-2

wait,sleep & yield

All the three functions wait, sleep and yield in java are related to threads but all of them do not belong to thread class. It is often confusing to distinguish between these three. Here is a quick difference between wait, sleep and yield functions:



WaitSleepYield
1.Method of class ObjectMethod of class ThreadMethod of class Thread
2.Non – StaticStaticStatic
3.Not invoked on a thread instanceInvoked on a thread instanceInvoked on a thread instance
4.Moves the thread to “wait’ stateMoves the thread to “wait” stateMoves the thread to “ready” state
5.Thread loose the ownership of the lockThread doesn’t loose the ownership of the lockThread doesn’t loose the ownership of the lock

Tuesday, March 11, 2014

What Are The Differences Between SAX and DOM Parsers?


The following are some fundamental differnces between a SAX and DOM model of parsing.

SAX:

1. Parses the document on node by node basis.
2. Does not store the XML in memory.
3. We can not insert or delete a node.
4. This model uses top to bottom traversing.
5. This model does not preserve comments.
6. It runs little faster than DOM

DOM

1. Stores the entire XML document into memory before processing
2. Occupies more memory
3. We can insert or delete nodes
4. This model can traverse in any direction.
5. This model preserves comments.
6. It runs slower than SAX model
So, when to choose what model to use?

Here is what you can do.

If you just need to read a node, but do not require to insert/delte node, then use SAX.
If you require node manipulation(insert/delete) nodes, use DOM.

Monday, March 3, 2014

Different types of JDBC Drivers


JDBC Driver is a software component that enables java application to interact with the database.
There are 4 types of JDBC drivers:


1.JDBC-ODBC bridge driver
2.Native-API driver (partially java driver)
3.Network Protocol driver (fully java driver)
4.Thin driver (fully java driver)

1) JDBC-ODBC bridge driver

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver. 

Advantages:

•easy to use.
•can be easily connected to any database.

Disadvantages:

•Performance degraded because JDBC method call is converted into the ODBC funcion calls.
•The ODBC driver needs to be installed on the client machine.
--------------------------------------------------------------------------------

2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java. 

Advantage:

•performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:

•The Native driver needs to be installed on the each client machine.
•The Vendor client library needs to be installed on client machine.
--------------------------------------------------------------------------------

3) Network Protocol driver

The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java.

Advantage:

•No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc.
Disadvantages:

•Network support is required on client machine.
•Requires database-specific coding to be done in the middle tier.
•Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be done in the middle tier.
--------------------------------------------------------------------------------

4)  Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language. 

Advantage:

•Better performance than all other drivers.
•No software is required at client side or server side.
Disadvantage:

•Drivers depends on the Database.

Object Cloning in Java



Object Cloning in Java

The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as follows:
protected Object clone() throws CloneNotSupportedException  

Why use clone() method ?

The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed that is why we use object cloning.

Advantage of Object cloning

Less processing task.

Example of clone() method (Object cloning)

  class Strudent implemants Cloneable
   {
      int rollno;
      String name;
    
      Student(int rollno,String name){
         this.rollno = rollno;
         this.name = name;
      }
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
     }

     public static void main(String args[]){

     try {
          
         Student s1 = new Student(101,"kumar");
         Student s2 = (Student)s1.clone();
         System.out.println(s1.rollno+" "+s1.name);
         System.out.println(s2.rollno+" "+s2.name);
   }
   Catch(CloneNotSupportedException c){    
    }
   }
Output:
             101 kumar
             101 kumar

Java Date examples

Convert Date to String.

 SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
 String date = sdf.format(new Date());
 System.out.println(date); //15/10/2013Example

Convert String to Date.

 SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
 String dateInString = "31-08-1982 10:20:56";
 Date date = sdf.parse(dateInString);
 System.out.println(date); //Tue Aug 31 10:20:56 SGT 1982

Get current date time

 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
 Date date = new Date();
 System.out.println(dateFormat.format(date)); //2013/10/15 16:16:39

Iterating Map in Java using KeySet Iterator && using EntrySet



HashMap
Set<String> keySet = loans.keySet();
Iterator<String> keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
   System.out.println("------------------------------------------------");
   System.out.println("Iterating Map using KeySet Iterator");
   String key = keySetIterator.next();
   System.out.println("key: " + key + " value: " + loans.get(key));
}

Output:
------------------------------------------------
Iterating Map using KeySet Iterator
key: home loan value: citibank
------------------------------------------------
Iterating Map using KeySet Iterator
key: personal loan value: Wells Fargo

Example for using EntrySet
Set<Map.Entry<String, String>> entrySet = loans.entrySet();
for (Entry entry : entrySet) {
   System.out.println("------------------------------------------------");
   System.out.println("looping HashMap in Java using EntrySet and java5 for loop");
   System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}

Output:
------------------------------------------------
looping HashMap in Java using EntrySet and java5 for loop
key: home loan value: citibank
------------------------------------------------
looping HashMap in Java using EntrySet and java5 for loop
key: personal loan value: Wells Fargo

What is the difference between Hashtable and HashMap?

import java.util.Iterator;
import java.util.Hashtable;
import java.util.Set;

public class HashtableEntriesIterator {

  public static void main(String[] args) {

    // Create a Hashtable and populate it with elements
    Hashtable hashtable = new Hashtable();
    hashtable.put("key_1","value_1");
    hashtable.put("key_2","value_2");
    hashtable.put("key_3","value_3");

    // Get a set of all the entries (key - value pairs) contained in the Hashtable
    Set entrySet = hashtable.entrySet();


    // Obtain an Iterator for the entries Set
    Iterator it = entrySet.iterator();
   
    // Iterate through Hashtable entries
    System.out.println("Hashtable entries : ");
    while(it.hasNext())

System.out.println(it.next());
   
  }
}

Difference between Comparator and Comparable in java


Comparable interface:

Class whose objects to be sorted must implement this interface.In this,we have to implement compareTo(Object) method.

For example:

public class Country implements Comparable<Country>{  
 @Override
 public int compareTo(Country country) {  
       return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ;  
 }}  

If any class implements comparable inteface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort().Object will be sort on the basis of compareTo method in that class.
Objects which implement Comparable in java can be used as keys in a SortedMap like TreeMap or SortedSet like TreeSet without implementing any other interface.

Comparator interface:

Class whose objects to be sorted do not need to implement this interface.Some third class can implement this interface to sort.E.g.CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id.

         Country indiaCountry=new Country(1, "India");  
         Country chinaCountry=new Country(4, "China");  
         Country nepalCountry=new Country(3, "Nepal");  
         Country bhutanCountry=new Country(2, "Bhutan");           

         List<Country> listOfCountries = new ArrayList<Country>(); 
         listOfCountries.add(indiaCountry);  
         listOfCountries.add(chinaCountry);  
         listOfCountries.add(nepalCountry);  
         listOfCountries.add(bhutanCountry);   
 
 //Sort by countryName  

           Collections.sort(listOfCountries,new Comparator<Country>() {  
                @Override 
                public int compare(Country o1, Country o2) {
                    return o1.getCountryName().compareTo(o2.getCountryName());  }  
            }); 

Sunday, March 2, 2014

Static Keyword

static keyword

The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
  1. variable (also known as class variable)
  2. method (also known as class method)
  3. block
  4. nested class

1) static variable

If you declare any variable as static, it is known static variable.
  • The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
  • The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable

class Student{   
     int rollno;   
     String name;   
     String college="ITS";   
}  

Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.If we make it static,this field will get memory only once.

static property is shared to all objects.

Example of static variable

  1. //Program of static variable   
  2.   
  3. class Student{   
  •    int rollno;   
  •    String name;   
  •    static String college ="ITS";   
  •       
  •    Student(int r,String n){   
  •    rollno = r;   
  •    name = n;   
  •    }   
  •  void display (){System.out.println(rollno+" "+name+" "+college);}   
  •   
  •  public static void main(String args[]){   
  •  Student s1 = new Student (111,"Karan");   
  •  Student s2 = new Student (222,"Aryan");   
  •     
  •  s1.display();   
  •  s2.display();   
  •  }   
  • }  
  • Output:111 Karan ITS
           222 Aryan ITS
    

    Program of counter without static variable

    In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count variable.
     
    1. class Counter{   
  • int count=0;//will get memory when instance is created   
  •   
  • Counter(){   
  • count++;   
  • System.out.println(count);   
  • }   
  •   
  • public static void main(String args[]){   
  •   
  • Counter c1=new Counter();   
  • Counter c2=new Counter();   
  • Counter c3=new Counter();   
  •   
  • }}  
  • Output:1
           1
           1
    

    Program of counter by static variable

    As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.
     
    1. class Counter{   
  • static int count=0;//will get memory only once and retain its value   
  •   
  • Counter(){   
  • count++;   
  • System.out.println(count);   
  • }   
  •   
  • public static void main(String args[]){   
  •   
  • Counter c1=new Counter();   
  • Counter c2=new Counter();   
  • Counter c3=new Counter();   
  •   
  • }}  
  • Output:1
           2
           3
    

    2) static method

    If you apply static keyword with any method, it is known as static method
    • A static method belongs to the class rather than object of a class.
    • A static method can be invoked without the need for creating an instance of a class.
    • static method can access static data member and can change the value of it.

    Example of static method

    //Program of changing the common property of all objects(static field).   
    1.   
    2. class Student{   
  •      int rollno;   
  •      String name;   
  •      static String college = "ITS";   
  •         
  •      static void change(){   
  •      college = "BBDIT";   
  •      }   
  •   
  •      Student(int r, String n){   
  •      rollno = r;   
  •      name = n;   
  •      }   
  •   
  •      void display (){System.out.println(rollno+" "+name+" "+college);}   
  •   
  •     public static void main(String args[]){   
  •     Student.change();   
  •   
  •     Student s1 = new Student (111,"Karan");   
  •     Student s2 = new Student (222,"Aryan");   
  •     Student s3 = new Student (333,"Sonoo");   
  •   
  •     s1.display();   
  •     s2.display();   
  •     s3.display();   
  •     }   
  • }  
  • Output:111 Karan BBDIT
           222 Aryan BBDIT
           333 Sonoo BBDIT