Tuesday, May 29, 2012

how to find whether jdk is 32 or 64 bit


package com.yagapp.phaseone;

public class Example1 {


public static void main(String args[]) {
 System.out.println("version ="
   + System.getProperty("sun.arch.data.model"));
}

}

Friday, May 25, 2012

what happens if u start a thread more than one time


package com.yagapp.phaseone;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Duplicate_List extends Thread{

/**
* @param args
*/
public void run(){

System.out.println("ramesh");
}

public static void main(String[] args) {

Duplicate_List t = new Duplicate_List();
t.start();
t.start();
t.start();
t.start();
t.start();
t.start();

}

}


this will give u run time exception according to the documentation of the Thread . start () methode

      1) It is never legal to start a thread more than once.
      2) In particular, a thread may not be restarted once it has completed execution.

Sunday, May 20, 2012

which one is better page directive or page action , in jsp


There are two include mechanisms available to insert a file in a JSP page. They are
1. include directive <%@ include file="child.jsp" %>
2. include action <jsp:include page="child.jsp" flush="true" />
The include directive includes the content of the file during the translation phase where as include action includes the content of the file during execution/request processing phase.
For include directive, JSP Engine adds the content of the inserted page at translation phase, so it does not have an impact on performance.
For include action, JSP Engine adds the content of the inserted page at run time which imposes extra overhead.


so for example for the page which you want to include is contains mostly static data , that can't be changed from one request to another request , then its better to use the 
include directive , because as i explained above , this page content will be included into the source jsp at the time of translation phase, and this phase will occur only one time in the life time of the jsp page, and there by it will increase the performance by decreasing the time to give response to the client request
syntax : < %@include file="myheader.jsp" %>

if ur page contains dynamic data which mostly changes from the request to request the better to use the include action as below

<jsp:include page="myResule.jsp" flush="true"/>


how to stop the creation of implicit session object in the jsp page

How to stop the creation of implicit session object in the jsp page ?

Why to stop the creation ?  and when to stop the creation ?

By using the page directive tag attributes u cab stop the creation of implicit object creation like below


<%@ page session="false" %>

remember that by default this attribute has the value true, means if don't specify any thing session object will be created by jsp engg.


<%@ page session="false" buffer="12kb" %>  , this tag will set the size of the out implicit object

how to set the how much response must go the client at once

response.setContentLength(int contentSize);


we have the api in the response implicit object , setContentLength(int size) , which decides the size of the out parameter 


syntax : response.setContentLength(int contentSize)

what is the meaning of out.flush() methode in jsp

consider the following lines below in the jsp service method  ,  _jspService()

out.write(<<some text>>);
out.write(<<some text1>>);
out.write(<<some text2>>);

in this case all the text in the write method will go at once to the client,
if u want the some text will go first then some text1 after that some text2 then we can have the logic like below


out.write(<<some text>>);
out.flush();
out.write(<<some text1>>);
out.flush();
out.write(<<some text2>>);
out.flush();


so here some text will go the client after first flush method with out waiting for the some text1.

that is the usage of flush method.

Saturday, May 19, 2012

performance wise difference among set map and list implementations

  Lists:
  1. Use ArrayList with proper initialization if you don't want thread safe for the collection whenever you  add/remove/access objects at end and middle of collection.
  2. Use Vector with proper initialization if you want thread safe for the collection whenever you  add/remove/access objects at end and middle of collection.
  3. Use LinkedList if you don't want thread safe for the collection whenever you  add/remove/access objects at beginning of collection.
  4. Use synchronized LinkedList if you want thread safe for the collection whenever you add/remove/access objects at beginning of collection.
  5. Use ListIterator than Iterator and Enumeration for List types
Sets:
  1. Use HashSet for maintaining unique objects if you don't want thread safe for the collection for all basic(add/remove/access) operations otherwise use synchronized HashSet for thread safe.
  2. Use TreeSet for ordered and sorted set of unique objects for non-thread safe collection otherwise use synchronized TreeSet for thread safe
Maps:
  1. Use HashMap for non-thread safe map collection otherwise use Hashtable for thread safe collection.
  2. Use TreeMap for non-thread safe ordered map collection otherwise use synchronized TreeMap for thread safe

how @Autowired in Spring will work

consider the following simple example


package com.yagapp.auto;

public class PointA {

private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}

--------------------------------------------------

package com.yagapp.auto;

import org.springframework.beans.factory.annotation.Autowired;

public class Circle {

private PointA point;

public PointA getPoint() {
return point;
}

@Autowired
public void setPoint(PointA point) {
this.point = point;
}
public void draw()
{
System.out.println("Circle drwan");
}
}
--------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
xmlns:context="http://www.springframework.org/schema/context">
<bean id="Circle" class="com.yagapp.auto.Circle"/>
<bean id="point1" class="com.yagapp.auto.PointA">
<property name="x" value="2"/>
<property name="y" value="3"/>
</bean>

</beans>
------------------------------------------------

package com.yagapp.auto;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestCircle {

/**
* @param args
*/
public static void main(String[] args) {
AbstractApplicationContext factory = new ClassPathXmlApplicationContext("Circle_Spring.xml");
Circle c = factory.getBean("Circle",Circle.class);
c.draw();

}

}


if execute this TestCircle  class , first spring will try to inject the Point object into Circle
how it will inject ?
here it will work with its default behavior 

auto wire by TYPE
means ?

spring first checks the configuration xml , for the bean which has the class value as com.yagapp.auto.PointA (and make sure we have only one such bean defined in the xml)
then it will create the bean and inject that bean into circle class

thats it we have a circle object with PointA object 

this is the way how @Autowired will work with its default behavior , auto wire by type

Executor Framework TIP # 3

how to make a thread pool will create the threads as and when a task is coming and no free thread is available
(please read the Executor Framework TIP # 2 , to understand more )

try to execute this code after understanding the TIP # 2


package com.yagapp.phaseone;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


class Task implements Runnable{
public void run(){
System.out.println("ramesh");

try {
Thread.sleep(900);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}

public class FixedThreadPoolExecutor {

/**
* @param args
*/


public static void main(String[] args) {


ExecutorService e = Executors.newCachedThreadPool();

e.execute(new Task());
e.execute(new Task());
e.execute(new Task());
e.execute(new Task());
e.execute(new Task());
e.execute(new Task());
e.execute(new Task());



}

}

Executor Framework Tip # 2

how to prove that ther is queue in the Thread pool which assigns one thread for each task , and when there are more number tasks than thread , then the task will be waited in the queue , and whenever a free thread is available in the queue , thread pool assigns a task from the queue to the free thread



 package com.yagapp.phaseone;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


class Task implements Runnable{
public void run(){
System.out.println("ramesh");

try {

// Here i am makeing the currenlty executing thread to sleep for some time so that thread has the monitor lock with it, and but at this time so many tasks waiting for the lock so eventually those will waited on the queue.

Thread.sleep(900);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}

public class FixedThreadPoolExecutor {

/**
* @param args
*/


public static void main(String[] args) {

/*
 * this will create 10 threads in the pool ,
 * which are waiting for the tasks to execute
 */
ExecutorService e = Executors.newFixedThreadPool(3);

e.execute(new Task());
e.execute(new Task());
e.execute(new Task());
e.execute(new Task());
e.execute(new Task());
e.execute(new Task());
e.execute(new Task());



}

}

Friday, May 18, 2012

Executor framework tip #1

what is the equivalent to   e.execute(r);       where e is the object of type Executor interface and r is the object of Runnable interface


(new Thread(r)).start(); =  e.execute(r);

that means  e.execute(r); , will create the thread the Thread Object , assign some task represented by Runnable interface object and start that thread


Wednesday, May 16, 2012

Priority Queue Simple Example


The PriorityQueue class implements the Queue interface. When items are added to a PriorityQueue they are not order by First In, First Out . Instead, all items in a PriorityQueue must be comparable (either by implement theComparable interface or by according to a Comparator) which is used to sort the items in the list.

How to declare and initialize a PriorityQueue



The example below shows you how to create a PriorityQueue of Strings. Since String implements Comparable, the Strings will be sorted by the compareTo() methods of the Strings in the Queue. A quick refresh on how compareTo() works for Strings: System.out.println("a".compareTo("ab")); prints out -1.
Note: The PriorityQueue adds and removes based on Comparable; however, if you iterate of the PriorityQueue you may not get the results that you expect. The iterator does not necessarilly go through the elements in the order of their Priority. In other words, if you want to see how the elements are added and removed, do not rely on an iterator. Use the remove() method of the priorityQueue class as is shown in the example code below. Priority Queue Demo
import java.util.*;

public class PriorityQueueDemo {

PriorityQueue<String> stringQueue;


public static void main(String[] args){

stringQueue = new PriorityQueue<String>();
  
stringQueue.add("ab");
stringQueue.add("abcd");
stringQueue.add("abc");
stringQueue.add("a");
 
//don't use iterator which may or may not 
//show the PriorityQueue's order
while(stringQueue.size() > 0)
       System.out.println(stringQueue.remove());
    
}

}
 




Output
a
ab
abc
abcd 

what is dirty read and phantom reads


DIRTY READS: Reading uncommitted modifications are call Dirty Reads. Values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction, thus getting you incorrect or wrong data.
This happens at READ UNCOMMITTED transaction isolation level, the lowest level. Here transactions running do not issue SHARED locks to prevent other transactions from modifying data read by the current transaction. This also do not prevent from reading rows that have been modified but not yet committed by other transactions.
To prevent Dirty Reads, READ COMMITTED or SNAPSHOT isolation level should be used.

Consider T1 and T2 , two transactions

T1 reads some data ,
 T2 modify the same data but not yet committed the transaction
again T1 reads the uncommitted data ,
 this situation called as Dirty read

because u don't know , whether T2 can roll back or commit its changes

T1 is reading the uncommitted data , so this is called as READ UNCOMMITTED, this can be solved by READ COMMITED isolation level
**************************________________________****************************

PHANTOM READS: Data getting changed in current transaction by other transactions is called Phantom Reads. New rows can be added by other transactions, so you get different number of rows by firing same query in current transaction.


In REPEATABLE READ isolation levels Shared locks are acquired. This prevents data modification when other transaction is reading the rows and also prevents data read when other transaction are modifying the rows. But this does not stop INSERT operation which can add records to a table getting modified or read on another transaction. This leads to PHANTOM reads.



PHANTOM reads can be prevented by using SERIALIZABLE isolation level, the highest level. This level acquires RANGE locks thus preventing READ, Modification and INSERT operation on other transaction until the first transaction gets completed.




what is non repeatable read


One of the ISO-ANSI SQL defined "phenomena" that can occur with concurrent transactions. If one transaction reads a row, then another transaction updates or deletes the row and commits, the first transaction, on re-read, gets modified data or no data. This is an inconsistency problem within a transaction and addressed by isolation levels.
    This is the non repeatable read, mean in a transaction , if your transaction don't get the same result of reads , then it is called as non repeatable read

Tuesday, May 15, 2012

what is @Transient annotation in hibernate

let consider the below java bean defination




package com.yagapps.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;


@Entity
public class College {


private String name;
private String address;
private String id;


public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

@Id
@Column(name="myname")
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Column(name="myadd")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}

hibernate will create a table with the name college which contains three columns, related to each field in the above java bean , but if u don';t want one field as a column in that table then u can make or associate @Transient annotation on that field as below



@Transient
public String getId() {
return id;
}




excellent link to java reflection mechanism

What does Class.forname method do?


A call to Class.forName("X") causes the class named X to be dynamically loaded (at runtime). A call to forName("X") causes the class named X to be initialized (i.e., JVM executes all its static block after class loading). Class.forName("X") returns the Class object associated with the "X" class. The returned Class object is not an instance of the "x" class itself.
Class.forName("X") loads the class if it not already loaded. The JVM keeps track of all the classes that have been previously loaded. This method uses the classloader of the class that invokes it. The "X" is the fully qualified name of the desired class.
For example,
package com.xyzws;
class AClass { 
    static { 
        System.out.println("static block in AClass");
    }
}

public class Program { 
    public static void main(String[] args) {
        try { 
            Class c   = Class.forName("com.xyzws.AClass"); 
        } catch (ClassNotFoundException e) {
        }
        
    }
}
The output is
static block in AClass
Here is one example that uses returned Class to create an instance of AClass:
package com.xyzws;
class AClass {
  public AClass() {
    System.out.println("AClass's Constructor");
  }
  static { 
    System.out.println("static block in AClass");
  }
}

public class Program { 
  public static void main(String[] args) {
    try { 
      System.out.println("The first time calls forName:");
      Class c   = Class.forName("com.xyzws.AClass"); 
      AClass a = (AClass)c.newInstance();

      System.out.println("The second time calls forName:");
      Class c1 = Class.forName("com.xyzws.AClass");

    } catch (ClassNotFoundException e) {
            ...
    } catch (InstantiationException e) {
            ...
    } catch (IllegalAccessException e) {
            ...
    }
        
  }
}
The output is
The first time calls forName:
static block in AClass
AClass's Constructor
The second time calls forName:  
//Calss has been loaded so there is not "static block in AClass" printing out

JDBC Driver Is a Good Example

You may have experience working with JDBC Drivers. For example, the classloader attempts to load and link the Driver class in the "org.gjt.mm.mysql" package. If successful, the static initializer is called.
Class.forName("org.gjt.mm.mysql.Driver");
Connection con = DriverManager.getConnection(url,?myLogin", "myPassword");
Let's see why you need Class.forName() to load a driver into memory. All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static an initializer only.
The MySQL JDBC Driver has a static initializer looks like this:
static {
    try {
        java.sql.DriverManager.registerDriver(new Driver());
    } catch (SQLException E) {
        throw new RuntimeException("Can't register driver!");
    }
}
JVM executes the static block and the Driver registers itself with the DriverManager.
You need a database connection to manipulate the database. In order to create the connection to the database, the DriverManager class has to know which database driver you want to use. It does that by iterating over the array (internally a Vector) of drivers that have registered with it and calls the acceptsURL(url) method on each driver in the array, effectively asking the driver to tell it whether or not it can handle the JDBC URL.

jsp implicit objects

ther are 9 implicit objects present in the jsp to be used in scripting elements

objectname     instance of the class
request                  javax.servlet.http.HttpServletRequest
response                javax.servlet.http.HttpServletResponse
session                  javax.servlet.http.HttpSession

application             java.servlet.ServletContext
config                    javax.servet.ServletConfig

exception               java.lang.Throwable (avalaible in only error pages)
page                      java.lang.Object

pageContext          javax.servlet.jsp.PageContext
out                        javax.servlet.jsp.JspWritter

DIfferent type of JDBC Drivers


JDBC Driver Types


JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)





4 types of jdbc drivers are elaborated in detail as shown below:

Type 1 JDBC Driver

JDBC-ODBC Bridge driver
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.

Type 1: JDBC-ODBC Bridge
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.

Type 2 JDBC Driver

Native-API/partly Java driver
The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific calls i.e. this driver is specific to a particular database. Some distinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will have oracle native api.

Type 2: Native api/ Partly Java Driver
Advantage
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type
1 and also it uses Native api which is Database specific.
Disadvantage
1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a database
4. Mostly obsolete now
5. Usually not thread safe.

Type 3 JDBC Driver

All Java/Net-protocol driver
Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.

Type 3: All Java/ Net-Protocol Driver
Advantage
1. This driver is server-based, so there is no need for any vendor database library to be present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast to load.
5. The type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.

Disadvantage
It requires another server application to install and maintain. Traversing the recordset may take longer, since the data comes through the backend server.

Type 4 JDBC Driver

Native-protocol/all-Java driver
The Type 4 uses java networking libraries to communicate directly with the database server.


Type 4: Native-protocol/all-Java driver
Advantage
1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform independence and eliminate deployment administration issues. It is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don't have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further, these drivers can be downloaded dynamically.
Disadvantage

With type 4 drivers, the user needs a different driver for each database.

ArratList and LinkedList

based on underline structure and which interfaces it is implementing we can understand which one to use , in which requirement



public class ArrayList<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable

means here Random access is very quick , if u want to access the elements rather than inserting or deleting then go with ArrayList

public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Queue<E>, Cloneable, Serializable

here Inserting and deleting at the begining or ending is very gud, so better to go LinkedList , if ur requriement is like that 


We can ignore Cloneable and Serializable as all of the JCF implement those. It’s also quite obvious that both of them implement the List interface, as they need to provide list functionability (backwards iteration, sub listing, etc).
Now for the differences: ArrayList is implementing RandomAccess while LinkedList implementing Queue. You could already tell something about the usage of the two classes.

ArrayList

Now for some implementation notes. The ArrayList is actually encapsulating an actualy Array, an Object[]. When you instanciate ArrayList, an array is created, and when you add values into it, the array changes its size accordingly. This gives you strengths and weaknesses:
  • Fast Random Access
  • You can perform random access without fearing for performence. Calling get(int) will just access the underlying array.
  • Adding values might be slow When you don’t know the amount of values the array will contain when you create it, a lot of shifting is going to be done in the memory space when the ArrayList manipulates its internal array.
  • Slow manipulation When you’ll want to add a value randomly inside the array, between two already existing values, the array will have to start moving all the values one spot to the right in order to let that happen.

LinkedList

The LinkedList is implemented using nodes linked to each other. Each node contains aprevious node link, next node link, and value, which contains the actual data. When new data is inserted, a node is inserted and the links of the surrounding nodes are updated accordingly. When one is removed, the same happens – The surrounding nodes are changing their links and the deleted node is garbage collected. This, as well, gives strengths and weaknesses:
  • Fast manipulation As you’d expect, adding and removing new data anywhere in the list is instantanious. Change two links, and you have a new value anywhere you want it.
  • No random access Even though the get(int) is still there, it now just iterates the list until it reaches the index you specified. It has some optimizations in order to do that, but that’s basically it.

Some Conclusions

ArrayList is very useful when a well defined set of data is needed in a List interface as opposed to an array. It can be dynamically changed, but try not to do so frequently throughout the life of the application. LinkedList is there for you to do just that:Manipulating it is very easy, and as long as its used for iteration purposes only and not for random accessing, it’s the best solution. Further, if you need random accessing from time to time, I suggest toArray for that specific moment.
Another point I didn’t raise here is the Queue issue. LinkedList implements extended abilities to the normal List interface which allows it to add and remove elements from its beginning and end. This makes the LinkedList perfect for Queue and Stack purposes – Although in Java 5 they already added a Stack class.

Monday, May 14, 2012

what is current_session_context_class in hibernate configuration xml

meaning and need for the current_session_context_class


When you create a hibernate session using any of the sessionFactory.openSession(...) methods the session factory will 'bind' the session to the current context. The default context is 'thread' which means the sesion factory will bind the session to the thread from which openSession(...) is called. 

This is useful because you can later call sessionFactory.getCurrentSession() which will return the session that is bound to the currently running thread. 

You can use other predefined current_session_context_class values such as 'jta' which will bind the session to the currently running JTA transaction (if you're running in an application server that supports JTA this is really useful). Or you can write your own implementation of org.hibernate.context.CurrentSessionContext and use that implementation to manage the current session context (not really advisable unless you absolutely need to). 

Sunday, May 13, 2012

DDL , DML and DCL and TCL


DDL


Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples:
  • CREATE - to create objects in the database
  • ALTER - alters the structure of the database
  • DROP - delete objects from the database
  • TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
  • COMMENT - add comments to the data dictionary
  • RENAME - rename an object

DML


Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:
  • SELECT - retrieve data from the a database
  • INSERT - insert data into a table
  • UPDATE - updates existing data within a table
  • DELETE - deletes all records from a table, the space for the records remain
  • MERGE - UPSERT operation (insert or update)
  • CALL - call a PL/SQL or Java subprogram
  • EXPLAIN PLAN - explain access path to data
  • LOCK TABLE - control concurrency

DCL


Data Control Language (DCL) statements. Some examples:
  • GRANT - gives user's access privileges to database
  • REVOKE - withdraw access privileges given with the GRANT command

TCL


Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.
  • COMMIT - save work done
  • SAVEPOINT - identify a point in a transaction to which you can later roll back
  • ROLLBACK - restore database to original since the last COMMIT
  • SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use