Saturday, December 13, 2014

Java Synchronization

Synchronization is the tool using which we can achieve thread safety, JVM guarantees that synchronized code will be executed by only one thread at a time. java keyword synchronized is used to create synchronized code and internally it uses locks on Object or Class to make sure only one thread is executing the synchronized code.
·         Java synchronization works on locking and unlocking of resource, before any thread enters into synchronized code, it has to acquire lock on the Object and when code execution ends, it unlocks the resource that can be locked by other threads. In the mean time other threads are in wait state to lock the synchronized resource.
·         We can use synchronized keyword in two ways, one is to make a complete method synchronized and other way is to create synchronized block.
·         When a method is synchronized, it locks the Object, if method is static it locks the Class, so it’s always best practice to use synchronized block to lock the only sections of method that needs synchronization.
·         While creating synchronized block, we need to provide the resource on which lock will be acquired, it can be XYZ.class or any Object field of the class.
·         synchronized(this) will lock the Object before entering into the synchronized block.
·         You should use the lowest level of locking, for example if there are multiple synchronized block in a class and one of them is locking the Object, then other synchronized blocks will also be not available for execution by other threads. When we lock an Object, it acquires lock on all the fields of the Object.
·         Java Synchronization provides data integrity on the cost of performance, so it should be used only when it’s absolutely necessary.
·         Java Synchronization works only in the same JVM, so if you need to lock some resource in multiple JVM environments, it will not work and you might have to look after some global locking mechanism.
·         Java Synchronization could result in deadlocks; check this post about deadlock in java and how to avoid them.
·         Java synchronized keyword cannot be used for constructors and variables.
·         It is preferable to create a dummy private Object to use for synchronized block, so that its reference can’t be changed by any other code. For example if you have a setter method for Object on which you are synchronizing, it’s reference can be changed by some other code leads to parallel execution of the synchronized block.

Monday, November 17, 2014

What is JDBC Driver ?


JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.

For example, using JDBC drivers enable you to open database connections and to interact with it by sending SQL or database commands then receiving results with Java.

The Java.sql package that ships with JDK contains various classes with their behaviours defined and their actual implementaions are done in third-party drivers. Third party vendors implements the java.sql.Driver interface in their database driver.

JDBC Drivers Types:

JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4, which is explained below:

Type 1: JDBC-ODBC Bridge Driver:

In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client machine. Using ODBC requires configuring on your system a Data Source Name (DSN) that represents the target database.

When Java first came out, this was a useful driver because most databases only supported ODBC access but now this type of driver is recommended only for experimental use or when no other alternative is available.

               The JDBC-ODBC bridge that comes with JDK 1.2 is a good example of this kind of driver.

Type 2: JDBC-Native API:

In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls which are unique to the database. These drivers typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge, the vendor-specific driver must be installed on each client machine.

If we change the Database we have to change the native API as it is specific to a database and they are mostly obsolete now but you may realize some speed increase with a Type 2 driver, because it eliminates ODBC's overhead.

.
                           The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3: JDBC-Net pure Java:

In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC clients use standard network sockets to communicate with an middleware application server. The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server.

This kind of driver is extremely flexible, since it requires no code installed on the client and a single driver can actually provide access to multiple databases.



You can think of the application server as a JDBC "proxy," meaning that it makes calls for the client application. As a result, you need some knowledge of the application server's configuration in order to effectively use this driver type.

Your application server might use a Type 1, 2, or 4 driver to communicate with the database, understanding the nuances will prove helpful.

Type 4: 100% pure Java:

In a Type 4 driver, a pure Java-based driver that communicates directly with vendor's database through socket connection. This is the highest performance driver available for the database and is usually provided by the vendor itself.

This kind of driver is extremely flexible, you don't need to install special software on the client or server. Further, these drivers can be downloaded dynamically.


MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their network protocols, database vendors usually supply type 4 drivers.

Which Driver should be used?

If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4.
If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver.
Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for your database.
The type 1 driver is not considered a deployment-level driver and is typically used for development and testing purposes only

Arraylist vs Vector in Java


1.  Synchronization and Thread-Safe

Vector is  synchronized while ArrayList is not synchronized  . Synchronization and thread safe means at a time only one thread can access the code .In Vector class all the methods are synchronized .Thats why the Vector object is already synchronized when it is created .

2.  Performance

Vector is slow as it is thread safe . In comparison ArrayList is fast as it is non synchronized . Thus     in ArrayList two or more threads  can access the code at the same time  , while Vector is limited to one thread at a time.

3. Automatic Increase in Capacity

A Vector defaults to doubling size of its array . While when you insert an element into the ArrayList ,      it increases
its Array size by 50%  .


By default ArrayList size is 10 . It checks whether it reaches the       last  element then it will create the new array ,copy the new data of last array to new array ,then old array     is garbage collected by the Java Virtual Machine (JVM) .

4. Set Increment Size

ArrayList does not define the increment size . Vector defines the increment size .

You can find the following method in Vector Class

public synchronized void setSize(int i) { //some code  }

There is no setSize() method or any other method in ArrayList which can manually set the increment size.

5. Enumerator

Other than Hashtable ,Vector is the only other class which uses both Enumeration and Iterator .While ArrayList can only use Iterator for traversing an ArrayList .

6.  Introduction in Java 

java.util.Vector  class was there in java since the very first version of the java development kit (jdk).
java.util.ArrayList  was introduced in java version 1.2 , as part of Java Collections framework . In java version 1.2 , Vector class has been refactored to implement the List Inteface .


Sunday, October 12, 2014

Difference between Struts1.X and Struts2.X


Difference Area
               Struts 1.X
               Struts 2.X
Action Class
In Struts 1 it's mandatory to extend org.apache.struts.action.Action and implement execute() method which returns ActionForward and accept HttpServletRequest and HttpServletResponse.
This is not the case with Struts 2, here Action class can be a simple POJO or Java object with execute() method. Also execute() method returns String rather than returning ActionForward object.  You can still use  ActionSupport class or Action interface but those are completely optional.
Configuration Files


Front Controller
In struts 1.x front controller is ActionServlet
In struts 2.x front controller is FilterDispatcher
Servlet Dependency
In action class, execute() method , it has HttpServletRequest and HttpServletResponse Object, both comes from servlet API
Not needed in struts 2 execute() method
No Action Form
Struts 1 uses an ActionForm object to capture input. Like Actions, all ActionForms must extend a base class. Since  other JavaBeans cannot be used as ActionForms, developers often create redundant classes to capture input. 
Struts 2 uses Action properties as input properties, eliminating the need for a second input object
Control Of Action Execution
Struts1 supports separate Request Processor (lifecycles) for each module, but all the Actions in a module must share the same lifecycle
Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks.

 Threading Model


Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts 1 Actions and requires extra care to develop. Action resources must be thread-safe or synchronized.
Struts2, Action objects are instantiated for each request, so there are no thread-safety issues

Tuesday, October 7, 2014

Java 8 Features

Java 8 release e.g. lambda expressions, functional interface, stream API, default methods and new Date and Time API. 

1. Lambda Expressions 
One of feature, which is synonymous to this release, is lambda expressions, which will provide ability to pass behaviours to methods. Prior to Java 8, if you want to pass behaviour to a method, then your only option was Anonymous class, which will take 6 lines of code and most important line, which defines the behaviour is lost in between. Lambda expression replaces anonymous classes and removes all boiler plate, enabling you to write code in functional style, which is some time more readable and expression.


Lambda Expressions Syntax


The basic syntax of a lambda is either:
(parameters) ->expression      or         (parameters) ->{ statements; }
The following are examples of Java lambda expression:
1. () -> 5          // takes no value and returns 5
2. x -> 2 * x        // takes a number and returns the result of doubling it
3. (x, y) -> x – y         // takes two numbers and returns their difference
4. (int x, int y) -> x + y // takes two integers and returns their sum
5.  (String s) -> System.out.print(s)   // takes a string and prints it to console without returning anything

Basic Lambdas Examples

Example 1- In this section, we will see how lambda expressions affect the way we code. Having a list of players, the “for loop”, as programmers often refers to the, for statement, can be translated in Java SE 8 as below:

String[] studentNames = {"Jeet", "Harsh", "Merry", "David", "Roger", "Andy ", "Tomas", "John"};
List<String> students =  Arrays.asList(studentNames);
       
// Old looping
for (String student : students) {
     System.out.print(student + "; ");
}       
// Using lambda expression and functional operations
students.forEach((student) -> System.out.print(student + "; "));

// Using double colon operator in Java 8
students.forEach(System.out::println);

Example 2 - As you saw, lambda expressions can reduced our code to one single line. Another example is in a graphical user interface application, when anonymous classes can be replaced with lambda expressions:

// using anonymous innerclass
button.setOnAction(new EventHandler<ActionEvent>() {
              @Override
                       public void handle(ActionEvent event) {
                                      System.out.println("Hello World!!"); 
            }
        });
 
// using lambda expression
button.setOnAction(event -> System.out.println("Hello World!!"));

Example 3 - Implementing the Runnable interface, see below how we can write Runnable using lambda expression:

// Using anonymous innerclass 
new Thread(new Runnable() {
        @Override
        public void run() {
               System.out.println("Hello world !!");
        }
}).start();
 
// Using lambda expression
new Thread(() -> System.out.println("Hello world !!")).start();
 
// Using anonymous innerclass
Runnable run1= new Runnable() {
        @Override
        public void run() {
               System.out.println("Hello world !!");
        }
};
 
// Using lambda expression
Runnable run2= () -> System.out.println("Hello world !!"); 
// Run em!
run1.run();
run2.run();



Friday, October 3, 2014

10 Frequently asked SQL Queries In Interviews


          In this article I am giving example of some SQL query which is asked in most the of interviews who is having one or  two year experience on this field .whenever you go for java developer position or any other programmer position  interviewee expect that if you are working from one or two years on any project definitely you come across to handle this  database query, so they test your skill by asking this type of simple query.

 Que 1: SQL Query to find second highest salary of Employee

  Ans : There are many ways to find second highest salary of Employee in SQL, you can either use SQL Join or Subquery     to solve this problem. Here is SQL query using Subquery :

 select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from Employee );


 Que 2: SQL Query to find Max Salary from each department.

 Ans :

 SELECT DeptID, MAX(Salary) FROM Employee  GROUP BY DeptID.


 Que 3: Write SQL Query to display current date.

  Ans: SQL has built in function called GetDate() which returns current timestamp.

 SELECT GetDate();


 Que 4: Write an SQL Query to check whether date passed to Query is date of given format or not.

  Ans: SQL has IsDate() function which is used to check passed value is date or not of specified format ,it returns 1(true)   or 0(false) accordingly.

 SELECT  ISDATE('1/08/13') AS "MM/DD/YY";


 It will return 0 because passed date is not in correct format.

 Que 5: Write a SQL Query to print the name of distinct employee whose DOB is between 01/02/2012 to 31/12/2013.

 Ans:
 SELECT DISTINCT EmpName FROM Employees WHERE DOB  BETWEEN ‘01/02/2012’ AND ‘31/12/2013’;

 Que 6:Write an SQL Query find number of employees according to gender  whose DOB is between 01/01/1960 to  31/12/1975.


  Ans : SELECT COUNT(*), sex from Employees  WHERE  DOB BETWEEN ‘01/01/1960 ' AND  ‘31/12/1975’ GROUP BY sex;

 Que 7:Write an SQL Query to find employee whose Salary is equal or greater than 20000.

 Ans : SELECT EmpName FROM  Employees WHERE  Salary>=20000;

 Que 8:Write an SQL Query to find name of employee whose name Start with ‘S’

 Ans: SELECT * FROM Employees WHERE EmpName like 'S%';

 Que 9: find all Employee records containing the word "John", regardless of whether it was stored as JOHN, John, or  john.

 Ans : SELECT  * from Employees  WHERE  upper(EmpName) like upper('john%');

Que 10: Write a SQL Query to find year from date.

Ans :  SELECT YEAR(GETDATE()) as "Year";