In my previous post I introduced JMS and Glassfish.
One of the outstanding actions from that post was to investigate how to handle errors, and effectively stop the processing of messages so the fault could be investigated.
I found that handling any JMSExceptions and introducing a MessageDrivenContext object allowed me to set the message for rollback. This had the effect of placing the current message back on the queue stack. Unfortunately with GlassFish this then seemed to enter an infinite loop of receiving the message, throwing the exception, placing the message back in the queue… receiving the message… and so on…
The recommended practice to prevent this behaviour seemed to surround setting an ActivationConfigProperty, namely endpointExceptionRedeliveryAttempts. However I couldn’t get this working on GlassFish at all. There were many Google results, albeit from a couple of years ago, with people facing similar issues. One of these results recommended a horribly solution of sleeping the bean processing for a period of time before trying again, which is the wart-and-all solution I’ve gone for at the moment. I’ll return to investigate this issue further!
So the source code for the MessageBean implementation now looks as follows:
@MessageDriven(mappedName="mqTest")
public class MessageBean implements MessageListener {
@Resource
private MessageDrivenContext mdc;
public MessageBean() {
}
public void onMessage(Message message) {
System.out.println("In onMessage()!");
try {
if (message instanceof ObjectMessage) {
ObjectMessage msg = (ObjectMessage) message;
Person received = (Person)msg.getObject();
System.out.println("Received Student: " + received.getFirstName() + " " +
received.getLastName());
// Pretend error has occurred
throw new JMSException("Dummy exception");
}
} catch (JMSException e) {
System.out.println("JMS Exception raised: " + e.toString());
mdc.setRollbackOnly();
try {
System.out.println("Sleeping for 5 seconds...");
Thread.sleep(5000);
System.out.println("...End of sleep");
} catch (InterruptedException ex) {
System.out.println("Thread sleep threw an interupt exception");
}
}
}
}





[...] of this blog will know I’ve struggled with Java and Message Queuing (see blog posts here, here, here and here). Normally by this point I would have given up, but having used Message Queuing to [...]