Friday, December 16, 2011


Sequences in 10G RAC

Recently we migrated our application to Oracle 10g RAC (3 Instance) and ended up with sequences created as out of order at each Instance.

Here is the snippet of code to demonstrate that.

rajesh@ORA10GR2-01> SELECT INST_ID,
  2    INSTANCE_NUMBER,
  3    INSTANCE_NAME
  4  FROM GV$INSTANCE
  5  ORDER BY INST_ID;

   INST_ID INSTANCE_NUMBER INSTANCE_NAME
---------- --------------- ----------------
         1               1 ORA10GR2-01
         2               2 ORA10GR2-02
         3               3 ORA10GR2-03


 rajesh@ORA10GR2-01> create sequence s CACHE 30;

Sequence created.

Elapsed: 00:00:00.07
rajesh@ORA10GR2-01> select SEQUENCE_NAME,ORDER_FLAG,CACHE_SIZE
  2  from user_sequences
  3  where sequence_name ='S'
  4  /

SEQUENCE_NAME                  O CACHE_SIZE
------------------------------ - ----------
S                              N         30

Elapsed: 00:00:00.17
rajesh@ORA10GR2-01>
rajesh@ORA10GR2-01>
rajesh@ORA10GR2-01> select s.nextval from dual;

   NEXTVAL
----------
         1

Elapsed: 00:00:00.14
rajesh@ORA10GR2-01>
rajesh@ORA10GR2-01> select s.nextval from dual;

   NEXTVAL
----------
         2

Elapsed: 00:00:00.25
rajesh@ORA10GR2-01>

When connecting back to Instance02 I found the sequence values different.

rajesh@ORA10GR2-01> connect rajesh/oracle@ORA10GR2-02
Connected.
rajesh@ORA10GR2-02> select s.nextval from dual;

   NEXTVAL
----------
        31

Elapsed: 00:00:00.48
rajesh@ORA10GR2-02>
rajesh@ORA10GR2-02> select s.nextval from dual;

   NEXTVAL
----------
        32

Elapsed: 00:00:00.15
rajesh@ORA10GR2-02>

When connecting back to Instance03 I found the sequence values different again.

rajesh@ORA10GR2-02> connect rajesh/oracle@ORA10GR2-03
Connected.
rajesh@ORA10GR2-03> select s.nextval from dual;

   NEXTVAL
----------
        61

Elapsed: 00:00:00.21
rajesh@ORA10GR2-03> select s.nextval from dual;

   NEXTVAL
----------
        62

Elapsed: 00:00:00.14
rajesh@ORA10GR2-03>
The reason for this out of order sequence at each instance is the sequence cache is in the shared pool, therefore sessions on the same node can share the cached entry, but sessions on different nodes cannot.

The solution to solve this sequence running out of order at each instance is to create sequence using ORDER option. which will guarantee the order in which numbers are generated.

rajesh@ORA10GR2-01> create sequence s CACHE 30 ORDER;

Sequence created.

Elapsed: 00:00:00.09
rajesh@ORA10GR2-01>
rajesh@ORA10GR2-01> select SEQUENCE_NAME,ORDER_FLAG,CACHE_SIZE
  2  from user_sequences
  3  where sequence_name ='S'
  4  /

SEQUENCE_NAME                  O CACHE_SIZE
------------------------------ - ----------
S                              Y         30

Elapsed: 00:00:00.10
rajesh@ORA10GR2-01>
rajesh@ORA10GR2-01> select s.nextval from dual;

   NEXTVAL
----------
         1

Elapsed: 00:00:00.17
rajesh@ORA10GR2-01> select s.nextval from dual;

   NEXTVAL
----------
         2

Elapsed: 00:00:00.34
rajesh@ORA10GR2-01>
Connecting back to Instance02.

rajesh@ORA10GR2-01> connect rajesh/oracle@ORA10GR2-02

Connected.
rajesh@ORA10GR2-02> select s.nextval from dual;

   NEXTVAL
----------
         3

Elapsed: 00:00:00.17
rajesh@ORA10GR2-02>
rajesh@ORA10GR2-02> select s.nextval from dual;

   NEXTVAL
----------
         4

Elapsed: 00:00:00.17
rajesh@ORA10GR2-02>
Connecting back to Instance03.

rajesh@ORA10GR2-02> connect rajesh/oracle@ORA10GR2-03
Connected.
rajesh@ORA10GR2-03> select s.nextval from dual;

   NEXTVAL
----------
         5

Elapsed: 00:00:00.14
rajesh@ORA10GR2-03>
rajesh@ORA10GR2-03> select s.nextval from dual;

   NEXTVAL
----------
         6

Elapsed: 00:00:00.17
rajesh@ORA10GR2-03>

We changed the sequence to "ordered" Now selecting on either node gets the next number as expected.

However having the sequence with CACHE and ORDER would lead to some performance implications due to cluster synchronization. In Oracle 10g RAC, if you specify the "ordered" clause for a sequence, then a global lock is allocated by the node when you access the sequence. This lock acquisition happens only at the first sequence access for the node, and subsequent uses of the sequence do not wait on this lock.


rajesh@ORA10GR2-01> create sequence s order;

Sequence created.

Elapsed: 00:00:00.01
rajesh@ORA10GR2-01>
rajesh@ORA10GR2-01> select SEQUENCE_NAME,ORDER_FLAG,CACHE_SIZE
  2  from user_sequences
  3  where sequence_name ='S';

SEQUENCE_NAME                  O CACHE_SIZE
------------------------------ - ----------
S                              Y         20

Elapsed: 00:00:00.01
rajesh@ORA10GR2-01>
rajesh@ORA10GR2-01>
Connected.
rajesh@ORA10GR2-01>

I was running the below Pl/SQL block evenly across all the RAC Instance.

rajesh@ORA10GR2-01>  declare
  2             k number;
  3             l_start number;
  4             l_cpu_time number;
  5     begin
  6             l_start := dbms_utility.get_time;
  7             l_cpu_time := dbms_utility.get_cpu_time;
  8     for i in 1..500000
  9     loop
 10                     select s.nextval
 11                     into k
 12                     from dual;
 13     end loop;
 14
 15             dbms_output.put_line (' Total Execution time = '|| (dbms_utility.get_time - l_start) );
 16             dbms_output.put_line (' Total CPU time = '|| (dbms_utility.get_cpu_time - l_cpu_time) );
 17     end;
 18  /

 Total Execution time = 82110
 Total CPU time = 7057

PL/SQL procedure successfully completed.

Elapsed: 00:13:40.99
rajesh@ORA10GR2-01>

And the AWR on Instance 1 is.

   SQL Id      Time (ms)
------------- ----------
9x2hyv1prpts9    802,038
Module: SQL*Plus
OUTPUT
--------------------------------------------------------------------------------
 declare k number; l_start number; l_cpu_time number; begin l_start :=
dbms_utility.get_time; l_cpu_time := dbms_utility.get_cpu_time; for i in 1..5
00000 loop select s.nextval into k from dual; end loop; dbms_outpu
t.put_line (' Total Execution time = '|| (dbms_utility.get_time - l_start) );
          -------------------------------------------------------------
SQL ID: 9x2hyv1prpts9              DB/Inst: IRDST01/irdst011  Snaps: 3518-3519
-> 1st Capture and Last Capture Snap IDs
   refer to Snapshot IDs witin the snapshot range
-> declare k number; l_start number; l_cpu_time number; begin l...
OUTPUT
--------------------------------------------------------------------------------
    Plan Hash           Total Elapsed                 1st Capture   Last Capture
#   Value                    Time(ms)    Executions       Snap ID        Snap ID
--- ---------------- ---------------- ------------- ------------- --------------
1   0                         802,038             1          3519           3519
          -------------------------------------------------------------
Plan 1(PHV: 0)
--------------
OUTPUT
--------------------------------------------------------------------------------
Plan Statistics                    DB/Inst: IRDST01/irdst011  Snaps: 3518-3519
-> % Total DB Time is the Elapsed Time of the SQL statement divided
   into the Total Database Time multiplied by 100
Stat Name                                Statement   Per Execution % Snap
---------------------------------------- ---------- -------------- -------
Elapsed Time (ms)                           802,038      802,037.9    30.0
CPU Time (ms)                                70,597       70,597.3    93.7
Executions                                        1            N/A     N/A
Buffer Gets                                 149,976      149,976.0    56.6
Disk Reads                                        3            3.0     7.7
OUTPUT
--------------------------------------------------------------------------------
Parse Calls                                       1            1.0     0.0
Rows                                              1            1.0     N/A
User I/O Wait Time (ms)                          45            N/A     N/A
Cluster Wait Time (ms)                      186,959            N/A     N/AApplication Wait Time (ms)                        0            N/A     N/A
Concurrency Wait Time (ms)                   13,813            N/A     N/AInvalidations                                     0            N/A     N/A
Version Count                                     1            N/A     N/A
Sharable Mem(KB)                                 20            N/A     N/A
          -------------------------------------------------------------

And the AWR on Instance 2 is.

                Elapsed
   SQL Id      Time (ms)
------------- ----------
9x2hyv1prpts9    818,718
Module: SQL*Plus
OUTPUT
--------------------------------------------------------------------------------
 declare k number; l_start number; l_cpu_time number; begin l_start :=
dbms_utility.get_time; l_cpu_time := dbms_utility.get_cpu_time; for i in 1..5
00000 loop select s.nextval into k from dual; end loop; dbms_outpu
t.put_line (' Total Execution time = '|| (dbms_utility.get_time - l_start) );
          -------------------------------------------------------------
SQL ID: 9x2hyv1prpts9              DB/Inst: IRDST01/irdst012  Snaps: 3518-3519
-> 1st Capture and Last Capture Snap IDs
   refer to Snapshot IDs witin the snapshot range
-> declare k number; l_start number; l_cpu_time number; begin l...
OUTPUT
--------------------------------------------------------------------------------
    Plan Hash           Total Elapsed                 1st Capture   Last Capture
#   Value                    Time(ms)    Executions       Snap ID        Snap ID
--- ---------------- ---------------- ------------- ------------- --------------
1   0                         818,718             1          3519           3519
          -------------------------------------------------------------
Plan 1(PHV: 0)
--------------
OUTPUT
--------------------------------------------------------------------------------
Plan Statistics                    DB/Inst: IRDST01/irdst012  Snaps: 3518-3519
-> % Total DB Time is the Elapsed Time of the SQL statement divided
   into the Total Database Time multiplied by 100
Stat Name                                Statement   Per Execution % Snap
---------------------------------------- ---------- -------------- -------
Elapsed Time (ms)                           818,718      818,718.5    31.7
CPU Time (ms)                                72,017       72,017.1    97.5
Executions                                        1            N/A     N/A
Buffer Gets                                 149,898      149,898.0    81.6
Disk Reads                                        0            0.0     0.0
OUTPUT
--------------------------------------------------------------------------------
Parse Calls                                       1            1.0     0.0
Rows                                              1            1.0     N/A
User I/O Wait Time (ms)                           0            N/A     N/A
Cluster Wait Time (ms)                      135,191            N/A     N/A
Application Wait Time (ms)                        0            N/A     N/A
Concurrency Wait Time (ms)                   14,768            N/A     N/A
Invalidations                                     0            N/A     N/A
Version Count                                     1            N/A     N/A
Sharable Mem(KB)                                 20            N/A     N/A
          -------------------------------------------------------------

And the AWR on Instance 3 is.

                Elapsed
   SQL Id      Time (ms)
------------- ----------
9x2hyv1prpts9    816,826
Module: SQL*Plus
OUTPUT
--------------------------------------------------------------------------------
 declare k number; l_start number; l_cpu_time number; begin l_start :=
dbms_utility.get_time; l_cpu_time := dbms_utility.get_cpu_time; for i in 1..5
00000 loop select s.nextval into k from dual; end loop; dbms_outpu
t.put_line (' Total Execution time = '|| (dbms_utility.get_time - l_start) );
          -------------------------------------------------------------
SQL ID: 9x2hyv1prpts9              DB/Inst: IRDST01/irdst013  Snaps: 3518-3519
-> 1st Capture and Last Capture Snap IDs
   refer to Snapshot IDs witin the snapshot range
-> declare k number; l_start number; l_cpu_time number; begin l...
OUTPUT
--------------------------------------------------------------------------------
    Plan Hash           Total Elapsed                 1st Capture   Last Capture
#   Value                    Time(ms)    Executions       Snap ID        Snap ID
--- ---------------- ---------------- ------------- ------------- --------------
1   0                         816,826             1          3519           3519
          -------------------------------------------------------------
Plan 1(PHV: 0)
--------------
OUTPUT
--------------------------------------------------------------------------------
Plan Statistics                    DB/Inst: IRDST01/irdst013  Snaps: 3518-3519
-> % Total DB Time is the Elapsed Time of the SQL statement divided
   into the Total Database Time multiplied by 100
Stat Name                                Statement   Per Execution % Snap
---------------------------------------- ---------- -------------- -------
Elapsed Time (ms)                           816,826      816,826.4    97.8
CPU Time (ms)                                68,859       68,858.5    90.9
Executions                                        1            N/A     N/A
Buffer Gets                                 133,660      133,660.0    28.3
Disk Reads                                        0            0.0     0.0
OUTPUT
--------------------------------------------------------------------------------
Parse Calls                                       1            1.0     0.0
Rows                                              1            1.0     N/A
User I/O Wait Time (ms)                           0            N/A     N/A
Cluster Wait Time (ms)                       25,148            N/A     N/A
Application Wait Time (ms)                        0            N/A     N/A
Concurrency Wait Time (ms)                    8,942            N/A     N/A
Invalidations                                     0            N/A     N/A
Version Count                                     1            N/A     N/A
Sharable Mem(KB)                                 20            N/A     N/A
          -------------------------------------------------------------

Due to the less CACHE sequence value and ORDER attribute and since the same sequence is shared across all Instance we ended up with Clustered & Concurrency waits.

Now repeting the same test with Increased CACHE size.

rajesh@ORA10GR2-01> create sequence s CACHE 100000 order;

Sequence created.

Elapsed: 00:00:00.03
rajesh@ORA10GR2-01>
rajesh@ORA10GR2-01> select SEQUENCE_NAME,ORDER_FLAG,CACHE_SIZE
  2  from user_sequences
  3  where sequence_name ='S';

SEQUENCE_NAME                  O CACHE_SIZE
------------------------------ - ----------
S                              Y     100000

Elapsed: 00:00:00.01 

rajesh@ORA10GR2-01>  declare
  2             k number;
  3             l_start number;
  4             l_cpu_time number;
  5     begin
  6             l_start := dbms_utility.get_time;
  7             l_cpu_time := dbms_utility.get_cpu_time;
  8     for i in 1..500000
  9     loop
 10                     select s.nextval
 11                     into k
 12                     from dual;
 13     end loop;
 14
 15             dbms_output.put_line (' Total Execution time = '|| (dbms_utility.get_time - l_start) );
 16             dbms_output.put_line (' Total CPU time = '|| (dbms_utility.get_cpu_time - l_cpu_time) );
 17     end;
 18  /

 Total Execution time = 32396
 Total CPU time = 3418

PL/SQL procedure successfully completed.

Elapsed: 00:05:23.96
rajesh@ORA10GR2-01>

AWR at Instance-01 shows

                Elapsed
   SQL Id      Time (ms)
------------- ----------
9x2hyv1prpts9    316,430
Module: SQL*Plus
OUTPUT
--------------------------------------------------------------------------------
 declare k number; l_start number; l_cpu_time number; begin l_start :=
dbms_utility.get_time; l_cpu_time := dbms_utility.get_cpu_time; for i in 1..5
00000 loop select s.nextval into k from dual; end loop; dbms_outpu
t.put_line (' Total Execution time = '|| (dbms_utility.get_time - l_start) );
          -------------------------------------------------------------
SQL ID: 9x2hyv1prpts9              DB/Inst: IRDST01/irdst011  Snaps: 3520-3521
-> 1st Capture and Last Capture Snap IDs
   refer to Snapshot IDs witin the snapshot range
-> declare k number; l_start number; l_cpu_time number; begin l...
OUTPUT
--------------------------------------------------------------------------------
    Plan Hash           Total Elapsed                 1st Capture   Last Capture
#   Value                    Time(ms)    Executions       Snap ID        Snap ID
--- ---------------- ---------------- ------------- ------------- --------------
1   0                         316,430             1          3521           3521
          -------------------------------------------------------------
Plan 1(PHV: 0)
--------------
OUTPUT
--------------------------------------------------------------------------------
Plan Statistics                    DB/Inst: IRDST01/irdst011  Snaps: 3520-3521
-> % Total DB Time is the Elapsed Time of the SQL statement divided
   into the Total Database Time multiplied by 100
Stat Name                                Statement   Per Execution % Snap
---------------------------------------- ---------- -------------- -------
Elapsed Time (ms)                           316,430      316,429.6    91.0
CPU Time (ms)                                34,199       34,198.8    87.9
Executions                                        1            N/A     N/A
Buffer Gets                                     118          118.0     0.9
Disk Reads                                        0            0.0     0.0
OUTPUT
--------------------------------------------------------------------------------
Parse Calls                                       1            1.0     0.1
Rows                                              1            1.0     N/A
User I/O Wait Time (ms)                           0            N/A     N/A
Cluster Wait Time (ms)                            4            N/A     N/AApplication Wait Time (ms)                        0            N/A     N/A
Concurrency Wait Time (ms)                        8            N/A     N/AInvalidations                                     0            N/A     N/A
Version Count                                     1            N/A     N/A
Sharable Mem(KB)                                 20            N/A     N/A
          -------------------------------------------------------------

AWR at Instance-02 shows

--------------------------------------------------------------------------------
 declare k number; l_start number; l_cpu_time number; begin l_start :=
dbms_utility.get_time; l_cpu_time := dbms_utility.get_cpu_time; for i in 1..5
00000 loop select s.nextval into k from dual; end loop; dbms_outpu
t.put_line (' Total Execution time = '|| (dbms_utility.get_time - l_start) );
          -------------------------------------------------------------
SQL ID: 9x2hyv1prpts9              DB/Inst: IRDST01/irdst012  Snaps: 3520-3521
-> 1st Capture and Last Capture Snap IDs
   refer to Snapshot IDs witin the snapshot range
-> declare k number; l_start number; l_cpu_time number; begin l...
OUTPUT
--------------------------------------------------------------------------------
    Plan Hash           Total Elapsed                 1st Capture   Last Capture
#   Value                    Time(ms)    Executions       Snap ID        Snap ID
--- ---------------- ---------------- ------------- ------------- --------------
1   0                         320,198             1          3521           3521
          -------------------------------------------------------------
Plan 1(PHV: 0)
--------------
OUTPUT
--------------------------------------------------------------------------------
Plan Statistics                    DB/Inst: IRDST01/irdst012  Snaps: 3520-3521
-> % Total DB Time is the Elapsed Time of the SQL statement divided
   into the Total Database Time multiplied by 100
Stat Name                                Statement   Per Execution % Snap
---------------------------------------- ---------- -------------- -------
Elapsed Time (ms)                           320,198      320,198.1    96.7
CPU Time (ms)                                36,561       36,561.4    92.0
Executions                                        1            N/A     N/A
Buffer Gets                                      59           59.0     0.7
Disk Reads                                        0            0.0     0.0
OUTPUT
--------------------------------------------------------------------------------
Parse Calls                                       1            1.0     0.1
Rows                                              1            1.0     N/A
User I/O Wait Time (ms)                           0            N/A     N/A
Cluster Wait Time (ms)                           12            N/A     N/A
Application Wait Time (ms)                        0            N/A     N/A
Concurrency Wait Time (ms)                        9            N/A     N/AInvalidations                                     0            N/A     N/A
Version Count                                     1            N/A     N/A
Sharable Mem(KB)                                 20            N/A     N/A
          -------------------------------------------------------------

AWR at Instance-03 shows

--------------------------------------------------------------------------------
 declare k number; l_start number; l_cpu_time number; begin l_start :=
dbms_utility.get_time; l_cpu_time := dbms_utility.get_cpu_time; for i in 1..5
00000 loop select s.nextval into k from dual; end loop; dbms_outpu
t.put_line (' Total Execution time = '|| (dbms_utility.get_time - l_start) );
          -------------------------------------------------------------
SQL ID: 9x2hyv1prpts9              DB/Inst: IRDST01/irdst013  Snaps: 3520-3521
-> 1st Capture and Last Capture Snap IDs
   refer to Snapshot IDs witin the snapshot range
-> declare k number; l_start number; l_cpu_time number; begin l...
OUTPUT
--------------------------------------------------------------------------------
    Plan Hash           Total Elapsed                 1st Capture   Last Capture
#   Value                    Time(ms)    Executions       Snap ID        Snap ID
--- ---------------- ---------------- ------------- ------------- --------------
1   0                         318,115             1          3521           3521
          -------------------------------------------------------------
Plan 1(PHV: 0)
--------------
OUTPUT
--------------------------------------------------------------------------------
Plan Statistics                    DB/Inst: IRDST01/irdst013  Snaps: 3520-3521
-> % Total DB Time is the Elapsed Time of the SQL statement divided
   into the Total Database Time multiplied by 100
Stat Name                                Statement   Per Execution % Snap
---------------------------------------- ---------- -------------- -------
Elapsed Time (ms)                           318,115      318,115.2    92.6
CPU Time (ms)                                31,745       31,745.2    83.8
Executions                                        1            N/A     N/A
Buffer Gets                                      47           47.0     0.0
Disk Reads                                        0            0.0     0.0
OUTPUT
--------------------------------------------------------------------------------
Parse Calls                                       1            1.0     0.1
Rows                                              1            1.0     N/A
User I/O Wait Time (ms)                           0            N/A     N/A
Cluster Wait Time (ms)                           11            N/A     N/A
Application Wait Time (ms)                        0            N/A     N/A
Concurrency Wait Time (ms)                        5            N/A     N/AInvalidations                                     0            N/A     N/A
Version Count                                     1            N/A     N/A
Sharable Mem(KB)                                 20            N/A     N/A
          -------------------------------------------------------------

Now the Cluster Wait Time & Concurrency Wait Time got reduced due to Increased CACHE size. which leads to less synchronization across RAC Instances.

Monday, December 12, 2011

Java Messaging Service - Consumer / Subscriber


package oc.test.olivia;


import javax.jms.*;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/*
 * @author Olivia Cassandrae
 */
public class Consumer {

    public static void main(String[] args) throws JMSException {
        ConnectionFactory connectionFactory
            = new ActiveMQConnectionFactory(url);
        Connection connection = connectionFactory.createConnection();
        connection.start();
        Session session = connection.createSession(false,
            Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue(subject);
        MessageConsumer consumer = session.createConsumer(destination);
        Message message = consumer.receive();
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            System.out.println("Received message '"
                + textMessage.getText() + "'");
        }
        connection.close();
    }
   
    // URL of the JMS server
    private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;
    private static String subject = "GROUNDOPS.PSCS.IROPS.BRIDGE.QUEUE";
}

Url: http://localhost:8161/admin



Java Messaging Service - Producer / Publisher

Exception:


ConnectionFactory is ::: org.apache.activemq.ActiveMQConnectionFactory
javax.jms.JMSException: Could not connect to broker URL: tcp://PDCHCL-TRAX9:61616. Reason: java.net.ConnectException: Connection refused: connect
at org.apache.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:35)
at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:278)
at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:222)
at org.apache.activemq.ActiveMQConnectionFactory.createQueueConnection(ActiveMQConnectionFactory.java:185)
at com.test.IROPSQueueApacheMQProducer.main(IROPSQueueApacheMQProducer.java:58)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.activemq.transport.tcp.TcpTransport.connect(TcpTransport.java:414)
at org.apache.activemq.transport.tcp.TcpTransport.doStart(TcpTransport.java:380)
at org.apache.activemq.util.ServiceSupport.start(ServiceSupport.java:50)
at org.apache.activemq.transport.TransportFilter.start(TransportFilter.java:57)
at org.apache.activemq.transport.TransportFilter.start(TransportFilter.java:57)
at org.apache.activemq.transport.WireFormatNegotiator.start(WireFormatNegotiator.java:72)
at org.apache.activemq.transport.TransportFilter.start(TransportFilter.java:57)
at org.apache.activemq.transport.TransportFilter.start(TransportFilter.java:57)
at org.apache.activemq.ActiveMQConnectionFactory.createActiveMQConnection(ActiveMQConnectionFactory.java:258)
... 3 more

This is the very first exception I got when I started to code my first JMS code. Due to wrong Listener Connection (IN red and green (my mistake of taking 9))


package oc.messageQ.olivia;

import java.io.File;
import java.io.FileInputStream;
import java.util.Hashtable;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;

public class IROPSQueueApacheMQProducer {

/**
* @author O Cassandrae
* @param args
*/
public static void main(String[] args) {
MessageProducer producer = null;
Connection conn = null;
Session jmsSession = null;

try {
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
                        //env.put(Context.PROVIDER_URL,"tcp://PDCHCL-TRAX9:61616");
env.put(Context.PROVIDER_URL,"tcp://PDCHCL-TRAX6:61616");
InitialContext context = new InitialContext(env);
ConnectionFactory cf = (ConnectionFactory) context
.lookup("ConnectionFactory");
System.out.println("ConnectionFactory is ::: "
+ cf.getClass().getName());

if (cf instanceof QueueConnectionFactory) {
conn = ((QueueConnectionFactory) cf).createQueueConnection();
jmsSession = ((QueueConnection) conn).createQueueSession(false,
Session.AUTO_ACKNOWLEDGE);
}
Destination dest = (Destination) context
.lookup("dynamicQueues/GROUNDOPS.PSCS.IROPS.BRIDGE.QUEUE");
System.out.println("dest is ::: " + dest);
            producer = ((QueueSession)jmsSession).createSender((Queue)dest);
            TextMessage message = jmsSession.createTextMessage();
            String AsmSource = "src/resources/IROPSFlightCancelled.xml";
            FileInputStream inputStream;
            byte[] readBytes;
            // build an asm  request
            inputStream = new FileInputStream(AsmSource);
            readBytes = new byte[Integer.valueOf(""+(new File(AsmSource)).length())];
            inputStream.read(readBytes);
            message.setText(new String(readBytes));
            //System.out.println("request: "+new String(readBytes));
            ((QueueSender)producer).send(message);
            //System.out.println("Message sent successfully!!!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(conn != null){
producer.close();
jmsSession.close();
conn.close();
}
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Please do start the bat file: C:\Software\apache-activemq-5.5.1\bin\activemq.bat (activemq.bat) before executing the program.

TransientObjectException - Hibernate 2

Transient Object Exception occurs due to two reasons:

1.  The below article will explain it. 

               Transient State

2. It occurs due to passing null as primary key. Check the class you are passing into the table is not null due to any logic. Therefore check the logic of the class it is throwing the exception.

The conversion of the transient state to persistent state in the method getHibernateTemplate();

Tuesday, December 6, 2011

TransientObjectException - hibernate

org.hibernate.TransientObjectException: object references an unsaved transient instance – save the transient instance before flushing: com.swacorp.pcs.common.model.ServiceLevel
<class name=”com.xxx.A” table=”A” schema=”TESTSCHEMA”>
<id name=”aId” type=”java.lang.Long”>
<column name=”A_ID” precision=”29? scale=”0? />
</id>
…………………..
some more mapping elements
…………………..
…………………..
<many-to-one name=”bId” class=”com.xxx.B” fetch=”select”>
<column name=”B_ID” precision=”29? scale=”0? />
</many-to-one>
…………………..
A is referring to B using a primary key column of bId of B.
In that post I have mentioned that if B is a transient object and you don’t want to persist the value of B to A then just tell the hibernate to ignore that value by saying
update=”false” insert=”false” in the many to one mapping.
But what if you want to persist the value of foreign key in A.
Then the approach is different. You have to make sure that instance B is persistent not transient.
That is if your code says something like
A a = new A();
B b = new B();
a.setB(b);
…..
…..
session.save(a);
you are in trouble. Because B is in transient state. You have to attach b to the session.
There may be other ways of attaching this transient object to session. The approach I am following is simple. I am reading the value of B from the database using Hibernate. That way, hibernate attaches B to session and it is then a persistent object.
That is I do something like
A a = new A();
B b = session.get(B.class, new Long(1));
a.setB(b);
…..
…..
session.save(a);
Hibernate defines and supports the following object states:

  * Transient :- an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned.

  * Persistent :- a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session.

  * Detached :- a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it persistent again.

My changes:
HibernateTemplate template = getHibernateTemplate();
   Session session = template.getSessionFactory().getCurrentSession();
   itmAndPaxItmEvntOccrs.paxItm.setSvcLvl((ServiceLevel)session.get(itmAndPaxItmEvntOccrs.paxItm.getSvcLvl().getClass(), new Long(1)));
   template.saveOrUpdate(itmAndPaxItmEvntOccrs.paxItm);

Sunday, October 16, 2011

Dont forget to validate your assumptions

There is just so much you can learn from customers (or potential customers) that you should spend at least one day a week talking to them. You'll be amazed at what you can learn.

Technical founders especially love dreaming up cool stuff and getting to coding.

This is a huge mistake.

I recently spoke to one of our customers and asked them what their favourite feature was. I was stunned when they mentioned that sending email when a comment was added was a killer feature for them.

The shock was because we always thought this feature as a commodity feature. I mean, every tool out there has the ability to send email when a comment is added. We had a whole lot of really killer features, but this was one of the key features??

So I probed further.

Turns out that other tools only send out emails for discussions that you are involved in. Our tool sends out emails for everything. Think of a mailing list - you get every email whether you participated or not. Whereas a forum only sends you notification for new replies in the threads where you participated. It was something like that.

We always thought sending email for everything was a limitation. It was on our roadmap to refine it and make it send email selectively.

Well, guess what? Rather than being a limitation, it was actually a feature! And a killer feature for them.

So I called another customer - and this was an important differentiating feature for them too!

In a startup, we make a ton of assumptions. Don't forget to get them validated. Usually what the customer thinks is important is not what you assumed it would be.

Twelve Reasons Why Businesses Fail

From Naeem Zafar's book Seven Steps to a Successful Startup:
  1. Solving a problem that most users are not willing to pay to solve your way
  2. Thinking that you can do it all by yourself
  3. Lacking trust among team members
  4. Being overconfident and not questioning yourself
  5. Lacking a crisp, singular focus&emdash;Trying to be everything to everyone
  6. Marketing myopia
  7. Confusing a hobby with a business
  8. Pricing incorrectly and not knowing your real competition
  9. Failing to properly define your market and customers
  10. Not having enough financial resources available
  11. Focusing on a market segment too small to sustain you
  12. Starting a business for the wrong personal reasons