Thursday, May 8, 2014

Tuesday, May 6, 2014

Get selected radio button value using jquery

if ($("input[name=in_invoicetype]:checked").val() == "Custom") {
   
                  alert("workTypeval====>" + $("input[name=in_invoicetype]:checked").val());
   
      }

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