# 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`

               InitialContext initialContext = getContext();

2. We look-up the JMS queue object from JNDI

               Queue queue = (Queue) initialContext.lookup("/queue/exampleQueue");

3. We look-up the JMS connection factory object from JNDI

               ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("/ConnectionFactory");

4. We create a JMS context but we do it inside the try-with-resources statement like so:

                try
                (
                   JMSContext jmsContext = cf.createContext()
                )

5. Inside the following try block we first create the producer

               JMSProducer jmsProducer = jmsContext.createProducer();

6. 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

              jmsProducer.send(queue, "this message will fail security!");

7. 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.

               System.out.println("expected exception from jmsProducer.send: " + e.getMessage());

8. And finally, we close the Initial Context, note we no longer have to worry about clearing up the JMSContext.

               finally
               {
                  if (initialContext != null)
                  {
                     initialContext.close();
                  }
               }