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;
}
@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();
}
}
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.