I'm using JMS (Apache Qpid) to create connections to a message broker. I do create some connections and cache those in a Map (Map<String, Connection>
). However, the message broker has its natural limits (in terms of resources like connections per user) which gets hit a some time. If I configure a connection via Qpid to use an idle timeout the connections in my map will constantly disconnect and connect again. Let's say the limit of connection is set to 3 and I create a 4th connection right in the moment when an idle timeout kicks in the 4th connection might connect and "steal" the connection. So the 4 connections will fight for the limit the message broker has. I've registered an exception listener and I do see the error occuring. I would like to close an connection on a specific error but it seems like I've no controll about that.
So how do I manage the lifecycle of a connection? Is there a way to get information about if a connection is connected or not?
I believe you should add some meta-data to your ExceptionListener
implementation in order to correlate it with the relevant connection. You could potentially use the same String
value which you use in your Map<String, Connection>
. You could also just set the Connection
directly in your ExceptionListener
implementation.
Aside from that you might reconsider creating multiple connections from your client in the first place. Generally speaking, one connection per client is sufficient. If you need to logically separate different tasks (e.g. producing & consuming) then you can create multiple sessions. This would have the benefit of simplifying your client application and using fewer resources on the broker.
Lastly, the JMS API doesn't provide any direct mechanism to test a connection's validity. In general it is safe to assume the connection is valid unless you receive an exception either synchronously or asynchronously via the ExceptionListener
.