I have a simple JMS client and I would like to close all the JMS related resources at the end, i.e. instances of MessageConsumer, Session, Connection. Each of these classes has a close() method that throws a JMSException. I read I have to close all of them and closing an instance of a Connection is not enough. So this is what I have so far:
try {
consumer.close();
session.close();
connection.close();
} catch (JMSException e) {
log.error(e.getMessage(), e);
}
but if for example a consumer.close() throws an exception the session and the connection won't be closed. So a more correct approach would be:
try {
consumer.close();
} catch (JMSException e) {
log.error(e.getMessage(), e);
}
try {
session.close();
} catch (JMSException e) {
log.error(e.getMessage(), e);
}
try {
connection.close();
} catch (JMSException e) {
log.error(e.getMessage(), e);
}
but it does not seem nice because of the code duplication. I find it hard to abstract it out more because none of these classes implement a common interface with a close() method (like Closable for example).
Do you know any better approach to close correctly all these 3 resources?