title: How to make MessageListener stop listening for messages in JMS when it receives a certain message?
body: <p>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.</p>
  
  <pre><code>public class MyListener implements MessageListener{
      MessageConsumer consumer;
  
      public MyListener(MessageConsumer mc){
          consumer = mc;
      }
  
      @Override
      public void onMessage(Message msg) {
          try{
              if(msg instanceof ObjectMessage){
                  consumer.close();
              }
              if (msg instanceof TextMessage){
                  TextMessage tmsg = (TextMessage) msg;
                  String xml = tmsg.getText();
                  // do some stuff                
              }
  
         }catch(Exception e){
             e.printStackTrace();
         }
      }
  </code></pre>