Using the JMS 1.1 API
to receive a message (JavaEESyncReceiverOld)

Here is a simple Java EE session bean which demonstrates how to use the JMS 1.1 API to synchronously receive a message.

@Stateless
@LocalBean
public class JavaEESyncReceiverOld {

    @Resource(lookup = "java:global/jms/demoConnectionFactory")
    ConnectionFactory connectionFactory;
    
    @Resource(lookup = "java:global/jms/demoQueue")
    Queue demoQueue;
    
    public String receiveMessageOld() {
        Connection connection = null;
        try {
            try {
                connection = connectionFactory.createConnection();
                connection.start();
                Session session = connection.createSession();
                MessageConsumer messageConsumer = session.createConsumer(demoQueue);
                TextMessage textMessage = (TextMessage) messageConsumer.receive(1000);
                if (textMessage==null){
                    return "Received null";
                } else {
                    return "Received "+textMessage.getText();
                }
            } finally {
                connection.close();
            }
        } catch (JMSException ex) {
            Logger.getLogger(JavaEESyncReceiverOld.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}

This example shows:

This example is for Java EE but the API for Java SE is similar

 Now compare this with using the JMS 2.0 simplified API to do the same thing

 Run this example

JMS 2.0 examples home