Sending messages to a JMS queue

I used openjms to develop this example. Download it, start up the server ( and create a queue testqueue (

The following example sends a TextMessage to the testqueue queue in PERSISTENT delivery mode, meaning that the JMS server will store the message on secondary storage to prevent loosing the message with server failures or crashes. The message stays there until delivered to all the consumers.

import javax.naming.*;
import java.util.*;
import javax.jms.*;
public class Main
   public static void main(String []args) throws Exception {
      // Load Context for OpenJMS
      Hashtable env = new Hashtable();
      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.CLIENT_ACKNOWLEDGE);
      Queue queue = session.createQueue("testqueue");
      QueueSender sender = session.createSender(queue);
      TextMessage textMsg = session.createTextMessage();
      textMsg.setText("Hello world!");
      System.out.println("Message sent!");