JMS Auto Closable Example

To run the example, simply type mvn verify from this directory, 
or mvn -PnoServer verify if you want to start and create the server manually.

This example shows you how JMS resources, such as connections, sessions and consumers, in JMS 2 can be automatically closed on error.

In this instance we auto close a connection after a subsequent call to a JMS producer send fails

Example step-by-step

  1. First we need to get an initial context so we can look-up the JMS connection factory and destination objects from JNDI. This initial context will get it's properties from the client-jndi.properties file in the directory ../common/config
  2.            InitialContext initialContext = getContext();
            
  3. We look-up the JMS queue object from JNDI
  4.            Queue queue = (Queue) initialContext.lookup("/queue/exampleQueue");
            
  5. We look-up the JMS connection factory object from JNDI
  6.            ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("/ConnectionFactory");
            
  7. We create a JMS context but we do it inside the try-with-resources statement like so:
  8.            
                try
                (
                   JMSContext jmsContext = cf.createContext()
                )
               
            
  9. Inside the following try block we first create the producer
  10.            JMSProducer jmsProducer = jmsContext.createProducer();
            
  11. We then try to send a message. It is this call that throws an exception as the producer doesn't have the privileges to send a message
  12.           jmsProducer.send(queue, "this message will fail security!");
           
  13. We catch the exception from the send message and can do what we want, however the JMSContext will have been closed prior to entering the catch block.
  14.            System.out.println("expected exception from jmsProducer.send: " + e.getMessage());
            
  15. And finally, we close the Initial Context, note we no longer have to worry about clearing up the JMSContext.
  16.            finally
               {
                  if (initialContext != null)
                  {
                     initialContext.close();
                  }
               }