Tuesday, November 30, 2010

Differences In Hibernate

Difference between Save and Persist

persist() makes a transient instance persistent. However, it does not guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time. persist() also guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. This is useful in long-running conversations with an extended Session/persistence context.

save() does guarantee to return an identifier. If an INSERT has to be executed to get the identifier ( e.g. "identity" generator, not "sequence"), this INSERT happens immediately, no matter if you are inside or outside of a transaction. This is problematic in a long-running conversation with an extended Session/persistence context

Differences between Load and Get

load() vs. get() :-

load()

get()

Only use the load() method if you are sure that the object exists.

If you are not sure that the object exists, then use one of the get() methods.

load() method will throw an exception if the unique id is not found in the database.

get() method will return null if the unique id is not found in the database.

load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.

get() will hit the database immediately.

Difference between Update and Merge

Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session

Sunday, November 28, 2010

Advanced JMS

The idea behind this post is to get accustomed with the advanced features of JMS. It is expected that the fundamentals of JMS is known to the reader.

  • Controlling message acknowledgment
  • Specifying message persistence
  • Setting message priority levels
  • Allowing messages to expire
  • Creating temporary destinations

Controlling message acknowledgment:

Until a JMS message has been acknowledged, it is not considered to be successfully consumed.

In nontransacted sessions, when and how a message is acknowledged depends on the value specified as the second argument of the createQueueSession or createTopicSession method. The three possible argument values are:

Session.AUTO_ACKNOWLEDGE. The session automatically acknowledges a client's receipt of a message either when the client has successfully returned from a call to receive or when theMessageListener it has called to process the message returns successfully. A synchronous receive in an AUTO_ACKNOWLEDGE session is the one exception to the rule that message consumption is a three-stage process. In this case, the receipt and acknowledgment take place in one step, followed by the processing of the message.

Session.CLIENT_ACKNOWLEDGE. A client acknowledges a message by calling the message's acknowledge method. In this mode, acknowledgment takes place on the session level: Acknowledging a consumed message automatically acknowledges the receipt of all messages that have been consumed by its session. For example, if a message consumer consumes ten messages and then acknowledges the fifth message delivered, all ten messages are acknowledged.

Session.DUPS_OK_ACKNOWLEDGE. This option instructs the session to lazily acknowledge the delivery of messages. This is likely to result in the delivery of some duplicate messages if the JMS provider fails, so it should be used only by consumers that can tolerate duplicate messages. (If it redelivers a message, the JMS provider must set the value of the JMSRedelivered message header to true.) This option can reduce session overhead by minimizing the work the session does to prevent duplicates.

If messages have been received but not acknowledged when a QueueSession terminates, the JMS provider retains them and redelivers them when a consumer next accesses the queue. The provider also retains unacknowledged messages for a terminated TopicSession with a durable TopicSubscriber. Unacknowledged messages for a nondurable TopicSubscriber are dropped when the session is closed.

Specifying message persistence:

The JMS API supports two delivery modes for messages to specify whether messages are lost if the JMS provider fails. These delivery modes are fields of the DeliveryMode interface.

You can specify the delivery mode in either of two ways.

If you do not specify a delivery mode, the default is PERSISTENT. Using the NON_PERSISTENT delivery mode may improve performance and reduce storage overhead, but you should use it only if your application can afford to miss messages.

Setting message priority levels :

You can use message priority levels to instruct the JMS provider to deliver urgent messages first. You can set the priority level in either of two ways.

The ten levels of priority range from 0 (lowest) to 9 (highest). If you do not specify a priority level, the default level is 4. A JMS provider tries to deliver higher-priority messages before lower-priority ones but does not have to deliver messages in exact order of priority.

Allowing messages to expire

By default, a message never expires. If a message will become obsolete after a certain period, however, you may want to set an expiration time. You can do this in either of two ways.

You can use the setTimeToLive method of the MessageProducer interface to set a default expiration time for all messages sent by that producer.

You can use the long form of the send or the publish method to set an expiration time for a specific message. The fourth argument sets the expiration time in milliseconds. For example, the following publish call sets a time to live of 10 seconds:

topicPublisher.publish(message, DeliveryMode.NON_PERSISTENT, 3, 10000);

If the specified timeToLive value is 0, the message never expires.

When the message is published, the specified timeToLive is added to the current time to give the expiration time. Any message not delivered before the specified expiration time is destroyed. The destruction of obsolete messages conserves storage and computing resources.

Creating temporary destinations

Normally, you create JMS destinations--queues and topics--administratively rather than programmatically. Your JMS or J2EE provider includes a tool that you use to create and to remove destinations, and it is common for destinations to be long lasting.

The JMS API also enables you to create destinations--TemporaryQueue and TemporaryTopic objects--that last only for the duration of the connection in which they are created. You create these destinations dynamically, using the QueueSession.createTemporaryQueue and the TopicSession.createTemporaryTopic methods.

The only message consumers that can consume from a temporary destination are those created by the same connection that created the destination. Any message producer can send to the temporary destination. If you close the connection that a temporary destination belongs to, the destination is closed and its contents lost.

You can use temporary destinations to implement a simple request/reply mechanism. If you create a temporary destination and specify it as the value of the JMSReplyTo message header field when you send a message, the consumer of the message can use the value of the JMSReplyTo field as the destination to which it sends a reply and can also reference the original request by setting the JMSCorrelationID header field of the reply message to the value of the JMSMessageID header field of the request.

Using JMS API Local Transactions

You can group a series of operations together into an atomic unit of work called a transaction. If any one of the operations fails, the transaction can be rolled back, and the operations can be attempted again from the beginning. If all the operations succeed, the transaction can be committed.

In a JMS client, you can use local transactions to group message sends and receives. The JMS API Session interface provides commit and rollback methods that you can use in a JMS client. A transaction commit means that all produced messages are sent and all consumed messages are acknowledged. A transaction rollback means that all produced messages are destroyed and all consumed messages are recovered and redelivered unless they have expired

A transacted session is always involved in a transaction. As soon as the commit or the rollback method is called, one transaction ends and another transaction begins. Closing a transacted session rolls back its transaction in progress, including any pending sends and receives.

In an Enterprise JavaBeansTM component, you cannot use the Session.commit and Session.rollback methods. Instead, you use distributed transactions.

You can combine several sends and receives in a single JMS API local transaction. If you do so, you need to be careful about the order of the operations. You will have no problems if the transaction consists of all sends or all receives or if the receives come before the sends. But if you try to use a request-reply mechanism, whereby you send a message and then try to receive a reply to the sent message in the same transaction, the program will hang, because the send cannot take place until the transaction is committed. Because a message sent during a transaction is not actually sent until the transaction is committed, the transaction cannot contain any receives that depend on that message's having been sent.

It is also important to note that the production and the consumption of a message cannot both be part of the same transaction. The reason is that the transactions take place between the clients and the JMS provider, which intervenes between the production and the consumption of the message. The sending of one or more messages to a queue by Client 1 can form a single transaction, because it forms a single set of interactions with the JMS provider. Similarly, the receiving of one or more messages from the queue by Client 2 also forms a single transaction. But because the two clients have no direct interaction, no transactions take place between them. Another way of putting this is that the act of producing and/or consuming messages in a session can be transactional, but the act of producing and consuming a specific message across different sessions cannot be transactional.

This is the fundamental difference between messaging and synchronized processing. Instead of tightly coupling the sending and receiving of data, message producers and consumers use an alternative approach to reliability, one that is built on a JMS provider's ability to supply a once-and-only-once message delivery guarantee.

When you create a session, you specify whether it is transacted. The first argument to the createQueueSession and the createTopicSession methods is a boolean value. A value of truemeans that the session is transacted; a value of false means that it is not transacted. The second argument to these methods is the acknowledgment mode, which is relevant only to nontransacted sessions. If the session is transacted, the second argument is ignored, so it is a good idea to specify 0 to make the meaning of your code clear. For example:

topicSession = topicConnection.createTopicSession(true, 0);

Because the commit and the rollback methods for local transactions are associated with the session, you cannot combine queue and topic operations in a single transaction. For example, you cannot receive a message from a queue and then publish a related message to a topic in the same transaction, because the QueueReceiver and the TopicPublisher are associated with aQueueSession and a TopicSession, respectively. You can, however, receive from one queue and send to another queue in the same transaction, assuming that you use the sameQueueSession to create the QueueReceiver and the QueueSender. You can pass a client program's session to a message listener's constructor function and use it to create a message producer, so that you can use the same session for receives and sends in asynchronous message consumers.

Saturday, November 20, 2010

SQL Basics - 3

Group By Clause

The Group By clause is used to group rows based on distinct values that exist for specified columns. The group by clause creates a data set containing several sets of records grouped together based on a condition

select AAA.JOB , aaa.ename, aaa.empno from EMP aaa where AAA.JOB is not null group by AAA.JOB , aaa.ename, aaa.empno;

This works both in Oracle and DB2. Its essential that the order of columns in select should have the same order in the group by clause

Having Clause

The Having clause is used in conjunction with the group by clause . It adds more filter into the group by . Having is different than the where clause as it cant be used without the group by. Also many functions like count, avg cannot be used in where clause whereas these functions can be used in the having clause

select AAA.JOB , aaa.ename, aaa.empno from EMP aaa where AAA.JOB is not null group by AAA.JOB , aaa.ename, aaa.empno having AAA.EMPNO>3000 ;

works both in Oracle and DB2. The Having clause can also work similar to the distinct clause , where the distinct eliminates duplicates but doesnot show which records where duplicated
the having clause can identify which values where unique or non unique. The following query can select customers with more than one account no

select cusno from accnts group by cusno having count(accnt_no) >1


SUBQUERIES

Subqueries are used within a query for select purposes, eg

select * from HR.EMPLOYEES where HR.EMPLOYEES.DEPARTMENT_ID in (select HR.DEPARTMENTS.DEPARTMENT_ID from HR.DEPARTMENTS where HR.DEPARTMENTS.LOCATION_ID=1700)

In the the above example all the records from the employee table is selected where the department id is those departments which have location id is 1700 in the department table

multiple column sub queries is also possible

select fname, lname from cust_mstr where (fname,lname) in (select fname,lname from emp_mstr)

Sub queries can also be used in the from clause . This represents a data source from that particular select statement.

select A.accnt_no, A.curbal, A.branch_no, B.avgbal from accnt_mstr A, (select branch_no avg(curbal) avgbal from accnt_mstr) B where A.branch_no= B.branch_no and A.curbal> B.avgBal

Sub Queries ca also be used in the order by clause

Exists/ Not Exists

The exists clause is similar to the in clause except the way it is executed






Saturday, November 6, 2010

The Lock API

The Java 5.0 comes with new features in the concurrency package to take care of the locking strategy. The previous locking in Java 2.0 had a lot of disadvantages, like once a thread is waiting for a lock its not possible to interrupt it. Also the thread will wait for ever if its not able to acquire the lock. The order of acquiring the lock is also dependent on the thread scheduler and there is no way we can force the scheduler to give a prticular thread more priority in acquiring a lock. Intrinsic lock also needs to be released in the same block in which it acquires the lock.

All the above problems has been answered in the updates in Java 5.0 with the advent of the Lock package. We can acquire a lock equivalent to a synchronized block by using the lock() method in the ReentrantLock class. The example of Blocking Queue with wait() notify() can be rewritten with the lock strategy.

public class BlockingQueue5 extends BlockingQueue {
 
   private Queue queue = new LinkedList();
     String testingwait = new String();
     Lock lock = new ReentrantLock();
     Condition notFull = lock.newCondition();
     Condition notEmpty = lock.newCondition();
     private int capacity;

     public BlockingQueue5(int capacity) {
      super(capacity);
         this.capacity = capacity;
     }

     public void put(T element) throws InterruptedException {
      lock.lock();
         try {
    while(queue.size() == capacity) {
     
     notFull.await();
        
    }
    
    queue.add(element);
    notEmpty.signal();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }finally{
    lock.unlock();
   }
     }

     public T take() throws InterruptedException {
      lock.lock();
         try {
    while(queue.isEmpty()) {
     
        notEmpty.await();
        
    }
    
    T item = queue.remove();
    notFull.signal();
    return item;
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }finally{
    lock.unlock();
   }
   return null;
     }

}

As can be seen the synchronized has been replaced by the lock(). Before any task is started the lock should be acquired . Its also imperative that the lock should be released come what may, so its essential that the release section should be in a  finally block. The wait and notify has been replaced by the Condition object. The await () and the signal()  methods  are equivalent to wait and notify. It necessary that the condition on which the await has been called , the signal is also called on the same condition.

Another method in the Lock class is the tryLock(). It solves the problems of deadlocking as seen in Dead Lock situation. The tryLock also comes with a overloaded method which takes in nanoseconds as parameters       which means the number of nano secs it will wait to acquire a lock after which it can resume with other operations. The tryLock acquires the lock if no other thread is waiting on that lock and in a thread ordering situation it gets the first preference. The  TransactionTryLock class below replaces the Transaction class and shows how tryLock can avoid deadlock situation.
public class TransactionTryLock extends Transaction{
 
 
private Lock accountA = new ReentrantLock();
private Lock accountB = new ReentrantLock();

public void transferA2B(){
 if(accountA.tryLock()) {
  System.out.println("lock for A held in A2B");
  try {
   // sleep given to force deadlock
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  if(accountB.tryLock()) {
   System.out.println("lock for B held in A2B");
   
  }

 }
}

public void transferB2A(){
 if(accountB.tryLock()) {
  System.out.println("lock for B held in B2A");
  try {
   // sleep given to force deadlock
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  if(accountA.tryLock()) {
   
   System.out.println("lock for A held in B2A");
   
  }

 }
}

}

Friday, November 5, 2010

Simulating a ordering deadlock

One of the major drawbacks of the synchronized keyword is the deadlock scenario. If we need to acquire locks on two objects Object A and Object B simultaneously and then work on them , we need to make sure that the order of acquiring the lock is maintained. If the Lock on Object A is acquired first and then on B then the code can be considered safe and deadlock resistant. If on the other hand the order is not guaranteed then code has the potential of reaching a dead lock, as the following code demonstrates. The Transaction class has two methods transferA2B and transferB2A where the lock is acquired in two different orders. A sleep time of 1 sec is set after acquiring the lock in the first object in each method.

Transaction class


public class Transaction {
private Object accountA = new Object();
private Object accountB = new Object();
public void transferA2B(){
synchronized (accountA) {
System.out.println("lock for A held in A2B");
try { // sleep given to force deadlock
Thread.sleep(1000);
} catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace();
}
synchronized (accountB) {
System.out.println("lock for B held in A2B");
}
}
}

public void transferB2A(){
synchronized (accountB) {
System.out.println("lock for B held in B2A");
try { // sleep given to force deadlock
Thread.sleep(1000);
} catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace();
} synchronized (accountA) {
System.out.println("lock for A held in B2A");
}
}
}
}

Two Threads A and B will call the individual methods of Transaction from the run method, so I am avoiding the code snippets for the threads

The DeadloackTest class


public class DeadlockTest {
public static void main(String[] args) {
Transaction tran = new Transaction();
Thread a = new Thread(new ThreadA(tran));
  Thread b = new Thread(new ThreadB(tran));  
a.start();  b.start(); 
}}

Thread Communication using wait() notify()

The following is a very simple example to demonstrate how multiple threads can communicate using the wait() notify () paradigms. The idea is to design a bounded Blocking Queue having a max size of 5. There will be two threads using the queue, where a thread will put 10 messages into the queue whereas the other will read the 10 messages. If the Queue has reached max size the Publisher thread has to wait till the queue has been read by the Consumer Thread. Similarly the Consumer thread will wait if the Queue is empty

BlockingQueue

public class BlockingQueue {

private Queue queue = new LinkedList();
String testingwait = new String();
private int capacity;

public BlockingQueue(int capacity) {
this.capacity = capacity;
}

public synchronized void put(T element) throws InterruptedException {
while(queue.size() == capacity) {
wait();
}

queue.add(element);
notifyAll();
}

public synchronized T take() throws InterruptedException {
while(queue.isEmpty()) {
wait();

}

T item = queue.remove();
notify();
return item;
}
}

MyThread


public class MyThread extends Thread {

BlockingQueue queue = null;
String threadname = null;


public MyThread(String threadname,BlockingQueue queue) {
super(threadname);
// TODO Auto-generated constructor stub
this.queue = queue;
this.threadname = threadname;
}



public void run() {
if(threadname.equals("PUTTINGTHREAD")){
for (int i = 0; i < 10; i++) {
try {
queue.put("value"+i);

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else{
for (int i = 0; i < 10; i++) {
try {
queue.take();

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



}

}





The Executable Class


public class TestThread {

public static void main(String[] args) {
BlockingQueue queue = new BlockingQueue(5);
Thread t = new MyThread("PUTTINGTHREAD",queue);
Thread t1 = new MyThread("TAKINGTHREAD",queue);
t.start();
t1.start();

}
}

Thursday, November 4, 2010

Difference between Alias and Synonym

An alias is an alternative to a synonym, designed for a distributed environment to avoid having to use the location qualifier of a table or view. Sysnonym can be used for the user who created it. But alias can be used for any users. Synonym is dropped when base table got dropped but alias will not get dropped. Synonym is recorded in the sys.synonym table and alias is recorded in sys.tables.

Tuesday, November 2, 2010

Difference between NoClassDefFoundError & ClassNotFoundException

java.lang.NoClassDefFoundError is thrown when we try create an object of a class and the runtime environment is not able to load the given class. This happens when we create the object using the new operator. The searched class though existed when the calling class was compiled but at run time the classloader wasn't able to find the binary code.

java.lang.ClassNotFoundException is thrown when a class is being loaded by the class loader. The class is presumed to be present in any the jar files located in the classpath,or lib. This exception is thrown when the forName method in the class or the findSystemClass/loadClass methods in the ClassLoader is being used.

The following program demonstrates the two , the first method createNew throws the NoClassDefFoundError and the second method loadClass throws ClassNotFoundException.


public class TestException {
public static void main(String[] args) {
createNew();
loadClass();
}
private static void createNew(){
FirstClass fc= new FirstClass();
}
private static void loadClass(){
try {
Class cla11 = Class.forName("collectionsTest.FirstClass");
FirstClass firstClass = (FirstClass)cla11.newInstance();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}


A very good post on this is provided here

SQL Basics - 2

ALTER Command :

The structure of the table can be modified by the alter command. Not only the structure but also columns can be added,deleted,data type modified, renamed with the alter table. Also Indexes, constraints can be added,deleted or modified.

ALTER table works by making a temporary copy of the original table. The alteration is performed on the copy , then the original table is deleted and the new one is renamed. While Alter table is executing , the original table is still readable to other oracle users.

Alter table ACCNTS ADD(user_lname varchar2(40), inst_dt date)

DB2 version : Alter table ACCNTS ADD column lname varchar(40)

Alter table ACCNTS DROP COLUMN inst_dt (in DB2 its not possible to drop a column from a table)

Alter table ACCNTS MODIFY (user_lname varchar2(100)) , this statement can modify both the data type and size

DB2 : Alter table ACCNTS alter column lname SET DATA TYPE varchar(200)


RENAME TABLE:

rename table ACCNTS to ACCOUNTS

TRUNCATE TABLE:

truncate table ACCNTS1

Truncate operations drop and re create the table which is much faster than deleting rows one by one
There is no truncate command in DB2, so the equivalent command in DB2 is

alter table accnts1 activate not logged initially with empty table;

DROP TABLE:

drop table ACCNTS1

SYNONYMS:

A synonym is an alternative name for objects such as tables,views , sequences

create or replace public synonym Chulbul for accnts.

(please check another post for difference between synonym and alias)

we can create synonym of any object from table,views,sequence,stored procs, functions even other synonymns. The synonym can also be dropped similar way

drop public synonym Chulbul


Monday, November 1, 2010

SQL Basics - 1

One Language that I have been using from my first project till this very day and still have no clue about is PL/SQL. So without wasting much time i would like to jump into the nitty gritties of core PL/SQL commands. I have Oracle 10g and DB2 EXPRESS C installed in my machine and using TOAD for oracle/DB2 for executing the commands. If a certain command is specific to Oracle or DB2 i will highlight the same.

Create Command :(DDL script)

create table ACCNTS (accnt_no number(16), accnt_name varchar2(100), balance number(10,2))

This will create an ACCNTS table with accnt_no, accnt_name, balance columns.

The equivalent command in DB2 would be

create table ACCNTS (accnt_no numeric(16), accnt_name varchar(100), balance numeric(10,2))

as number and varchar2 are not valid datatypes in db2

INSERT Command : (DML script)

insert into ACCNTS (accnt_no,accnt_name, balance) values (1, 'tatha', 10.00)

this command will insert the said values in the ACCNTS table. Its not necessary to give the column names as we are inserting all the values. If we choose not to insert all the values then we have to mention the column names and its not bound by any order.

It is also possible to insert data

SELECT Command : (DML script)

select * from ACCNTS or select accnt_no,accnt_name from ACCNTS.

This very obvious what this command will do.

WHERE Clause :

the where clause acts as a filter criteria

select * from ACCNTS where accnt_no > 10 or
select accnt_no from ACCNTS where accnt_name='tatha'

DELETE Command :

To delete all the rows of a table the command

delete from ACCNTS , for selective deletion the where clause can be used
UPDATE Command :

To update the values in a table the update command is used

update ACCNTS set accnt_name = 'Roy' where accnt_no=11

DISTINCT Clause :

distinct can be used when we require to eliminate duplicates. Suppose we have two records in the ACCNT table with name as tatha, and we want to view distinct names, the query is

select distinct accnt_name from ACCNTS

ORDER BY Clause :

To order the result we use the ORDER BY clause. The order can be both DESC and ASC. Suppose we want to order the balance in a descending order

select * from ACCNTS order by balance desc;

AS SELECT Clause
It is also possible to create a table from the data of another table, for example if we want to create a table ACCNT_DET which has accnt_no and accnt_name from ACCNTS

create table ACCNT_DET (accnt_no,accnt_name) as select accnt_no, accnt_name from ACCNTS

This command doesnt work in DB2 database, the equivalent command in DB2 database consists of two commands

Create table new_table like old_table;
Insert into new_table select * from old table

The second command can be used in Oracle to insert into a table values from another table like

Insert into ACCNT_DET select accnt_no_accnt_name from ACCNTS