Friday, March 13, 2015

Transaction Management in JMS



          By Default JMS auto Transactyions are auto committed.  Session is actually taken care the Transaction Mgmt in JMS.

To enable Transaction mgmt ,Set "true" to the first parameter While creating a session from connection.

Set  "false" to the first parameter While creating a session from connection and try following statement.

    QueueSession qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    qsession.rollback();

It will cause the following exception,

com.ibm.msg.client.jms.DetailedIllegalStateException: JMSCC0014: It is not valid to call the 'rollback' method on a nontransacted session. The application called a method that must not be called on a nontransacted session. Change the application program to remove this behavior.

Set "true" to the first parameter While creating a session from connection and try following statement.

    QueueSession qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
   
    <send a message 1>
    <send a message 2>
    <send a message 3>

    qsession.rollback();

Browse the above message in the MQ Explorer and find out the result.

Following Program explain the Transaction mgmt in JMS

import javax.jms.*;
import java.util.Hashtable;
import javax.naming.*;
import java.io.*;
public class JMSTransactionDemo
{
    public static void main(String args[])
    {
      
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter 10 Messages ......");

            Hashtable ht = new Hashtable();
            ht.put(Context.PROVIDER_URL,"file:/C:/JNDI-Directory");
            ht.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.fscontext.RefFSContextFactory");
            Context ctx = new InitialContext(ht);
          
            QueueConnectionFactory qcf = (QueueConnectionFactory)ctx.lookup("MY_QCF");
          
            Queue qu = (Queue) ctx.lookup("MY_Q");

            QueueConnection qcon = qcf.createQueueConnection();

            //QueueSession qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            QueueSession qsession = qcon.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);

            QueueSender qSender =  qsession.createSender(qu);
          
            for(int i=0;i<=10;i++){    

                TextMessage msg =  qsession.createTextMessage();
              
                String line = br.readLine();

                msg.setText(line );
              
          
                qSender.send(msg);

                if(i==5)
                    qsession.rollback();

                if(i==10)
                    qsession.commit();
            }

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

0 comments:

Post a Comment