How to control acknowledgement
So far, all examples created the Session in AUTO_ACKNOWLEDGE mode. This means that a message is automatically acknowledged when the client either polls it or the MessageListener is called with the message as argument. The effect of the acknowledgement is that the message is removed from the queue and you won't receive it again. However, this is not always desired. If processing the message fails, for whatever reason, you may want it to stay in the queue and process it later. Then you should switch to CLIENT_ACKNOWLEDGE, which requires calling the method Message.acknowledge for every received message. If you don't call it, you will receive the message again.
Connection con = ...;
Queue queue = ...;
Session session = con.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queue);
con.start();
while (true) {
Message msg = consumer.receive();
// do something with the message...
msg.acknowledge();
}
Beside AUTO_ACKNOWLEDGE and CLIENT_ACKNOWLEDGE there is also a third mode called DUPS_OK_ACKNOWLEDGE. It works like CLIENT_ACKNOWLEDGE, requiring you to acknowledge explicitly, but in this mode it may sometimes happen that you receive an already acknowledged message again. The advantage of this mode is that it may be faster when you receive a large number of messages.
Note: with message-driven beans you don't need to care about the acknowledgement mode. They run neither in AUTO_ACKNOWLEDGE nor in CLIENT_ACKNOWLEDGE mode, but inside a transaction (enabled using createSession's first argument). The message is acknowledged when the EJB's transaction is committed.