# JMS Completion Listener 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 to send a message asynchronously to ActiveMQ Artemis and use a CompletionListener to be notified of the Broker receiving it

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

               jmsContext = cf.createContext();

5. We create a JMS Producer.

               JMSProducer producer = jmsContext.createProducer();

6. We set a CompletionListener on the Producer

              producer.setAsync(new CompletionListener()
                    {
                       @Override
                       public void onCompletion(Message message)
                       {
                          System.out.println("message acknowledged by ActiveMQ");
                          latch.countDown();
                       }

                       @Override
                       public void onException(Message message, Exception e)
                       {
                          e.printStackTrace();
                       }
                    });

7. We send a message

               producer.send(queue, "this is a string");

8. and then wait for the Completion Listener to be called

               return latch.await(5, TimeUnit.SECONDS);

9. And finally, always remember to close your JMS connections and resources after use, in a `finally` block. Closing a JMS connection will automatically close all of its sessions, consumers, producer and browser objects

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