Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the message again coming to onMessage() function?

I am using ActiveMQ to send the message.

So when I sent a message, the message comes to receive message. On successful insertion, it is acknowledged.

But I have code after acknowledgement, which can throw NullPointerException.

So to produce that exception intentionally, I have thrown NullPointerException. So when it does that:

Message is not dequeued and the same message comes again to the onMessage function.

My code is:

public void onMessage(Message message) {
    String msg = null;
    try
    {
        msg = receiveMessage(message);

        // Other code to insert message in db

        message.acknowledge();

        if(true)
        {
            throw new NullPointerException("npe"));
        }
            ** // Other code which might produce a null pointer exception **
        }
        catch(Exception ex)
        {
        }
    }

Why is the message again coming to onMessage() function as I have acknowledge() it also.

Since I have already inserted the message in db.

Doesn't the message inside queue will be removed on acknowledge()?

How I can achieve this?

like image 751
vikiiii Avatar asked Sep 14 '12 12:09

vikiiii


2 Answers

You use AUTO acknowledge mode with message listners, then by specification, a message is redelivered if the message listeners fails to return successfully (for instance if there is an exception thrown).

In your case, you are trying to manually acknowledge the message, but that is not possible using a session created with createSession(false, Session.AUTO_ACKNOWLEDGE).

Your code would have worked with Session.CLIENT_ACKNOWLEDGE.

Otherwise, you want to catch the exceptions inside the onMessage method, while using AUTO_ACKNOWLEDGE.

To get a more fine grained controll over your messages, please consider using transacted sessions and use session.commit(); to confirm a message has been read.

like image 181
Petter Nordlander Avatar answered Nov 15 '22 16:11

Petter Nordlander


Have you checked that you are not using transacted sessions?. When using transacted sessions,the acknowledge mode is ignored, so:

  • Your message.acknowledge() would effectively be a no-op

  • Your uncaught exception would be triggering a "session rollback" when escaping your message listener, forcing redelivery of the message.

NOTE: Your published code has a catch (Exception ex) { }, so I don't know exactly how your exception escapes outside.

like image 36
gpeche Avatar answered Nov 15 '22 17:11

gpeche