Receiving messages asynchronously from a JMS queue

I used openjms to develop this example. Check out this Q&A first!

The following example receives a message asynchronously from the testqueue queue. The acknowledgement mode is set to AUTO_ACKNOWLEDGE, which means that the session will automatically acknowledges a client’s receipt of a message. With asynchronous reception, the onMessage method of your implementation of MessageListener is called when there is a message available on the queue.

To receive message synchronously, check this Q&A.

Main.java:

import javax.naming.*;
import java.util.*;
 
import javax.jms.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      Hashtable env = new Hashtable();
      env.put(Context.INITIAL_CONTEXT_FACTORY,"org.exolab.jms.jndi.rmi.RmiJndiInitialContextFactory");
      env.put(Context.PROVIDER_URL, "rmi://localhost:1099/JndiServer");
      Context ctx = new InitialContext(env);
  
      QueueConnectionFactory cnxFactory = (QueueConnectionFactory) ctx.lookup("JmsQueueConnectionFactory");
 
      Connection connection = ((QueueConnectionFactory) cnxFactory).createQueueConnection();
      QueueSession session = ((QueueConnection) connection).createQueueSession(
                                   false, Session.AUTO_ACKNOWLEDGE);
      Queue queue = session.createQueue("testqueue");
      QueueReceiver receiver = session.createReceiver(queue);
  
      MyMessageConsumer consumer = new MyMessageConsumer();
      receiver.setMessageListener(consumer);
 
      connection.start();
   }
}
 
class MyMessageConsumer implements MessageListener
{
   public void onMessage(Message message) {
      System.out.println("Message received: " + message);
   }
}