Receiving messages synchronously from a JMS queue

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

The following example receives a message 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. It also receives message synchronously: the call to receiver.receive() is a blocking call. However, you can also use the variation receiver.receive(long) where you can specify a timeout. The call will then only block for that specified value.

To receive messages asynchronously, check out 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);
  
      connection.start();
 
      // blocks until message received
      Message message = receiver.receive();
      System.out.println("Message received: " + message);

      System.exit(1);
   }
}