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

vikiiii picture vikiiii · Sep 14, 2012 · Viewed 8.2k times · Source

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?

Answer

Petter Nordlander picture Petter Nordlander · Sep 14, 2012

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.