Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.jms.MessageConsumer hangs on receive when consumer closed

Tags:

java

jms

ibm-mq

According to the javadoc, if I call receive() on a javax.jms.MessageConsumer it will block indefinitely until a message is produced or until the message consumer is closed.

I have a thread in which a receive() is being called. As part of the thread shutdown I am calling close(), but the consumer still blocks in receive() and so the thread will not shutdown. The gist of my code is:

public String receiveMessage() {
...
...
   System.out.println("About to receive")
   TextMessage message = (TextMessage) consumer.receive();
   System.out.println("No longer receiving")
...
...
}

public void stop() {
    try {
        if (consumer != null) {
            consumer.close();
        }
    } catch (JMSException ex) {
        throw new IllegalStateException(ex);
    }
}

In the debugger I can see close() being called, but the receive still blocks. If I use the receive() method with a timeout it will block until the timeout expires.

Everything looks right to me, hopefully someone can tell me what I am doing wrong.

like image 760
Dave Richardson Avatar asked Nov 04 '11 09:11

Dave Richardson


2 Answers

I've sorted the problem, I wasn't doing a connection.start() anywhere. Once I put this in, the MessageConsumer.receive() stopped blocking when I closed it and everything worked as I had expected.

Thanks for your suggestions.

like image 159
Dave Richardson Avatar answered Oct 04 '22 19:10

Dave Richardson


One further thought.

In JMS, Connection is multi-threaded. Session and below (Consumer, Producer, Message, etc) are not thread-safe. If you're accessing any of that non-thread-safe stuff from multiple threads, you're responsible for avoiding multi-threaded access.

The code you show below looks like you're calling methods on Consumer from a couple of threads. A violation of that rule.

It might be safer to just close the Connection object. No threading conflicts and any sensible implementation would do the right thing to clean up resources associated w/ the Connection.

like image 23
John M Avatar answered Oct 04 '22 18:10

John M