How to make MessageListener stop listening for messages in JMS when it receives a certain message?

I have a message listener that is receiving some TextMessages. When it receives an ObjectMessage, I want it to stop listening to the queue. My problem is that when I call, consumer.close() inside the onMessage(Message msg) method, the ObjectMessage does not seem to be removed from the Queue. If I use some marker to tell the consuemr to close after the onMessage() method, the listener may consume another message before it actually closes. Any suggestions? Here is some code. The Session, Connection, and InitialContext have not been closed yet.

public class MyListener implements MessageListener{
    MessageConsumer consumer;

    public MyListener(MessageConsumer mc){
        consumer = mc;

    public void onMessage(Message msg) {
            if(msg instanceof ObjectMessage){
            if (msg instanceof TextMessage){
                TextMessage tmsg = (TextMessage) msg;
                String xml = tmsg.getText();
                // do some stuff                

       }catch(Exception e){


Do not use an asynchronous MessageListener.

Instead use the normal synchronous receive method in your main thread in a loop. If you get your special message, you can acknowledge and break from the loop to close the session, and to terminate the program.

Leave a Reply

Your email address will not be published. Required fields are marked *