Search code examples
javanullpointerexceptionjmslisteneractivemq-classic

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?


Solution

  • You can create a separate method for processing the message, by which I mean that in the onMessage() function write code for only insertion of that message into the database.

    And create a separate function for the processing of that message.

    So that if you get any error during processing, the message will not come to onMessage() again.