views:

21

answers:

1

I am opening a JMX Connection using getMBeanServerConnection() method and then closing it after use in a finally block. And, for a given JMX Connector, 2 successful calls to getMBeanServerConnection() usually returns the same MBeanServerConnection.

Some of the operations are invoked concurrently, and each of them invokes getMBeanServerConnection(). But, they get the SAME connection. And, therefore, when the first operation completes, the remaining operation fails with "Connection Closed" error.

How can I go about resolving this? Should I create multiple connector objects and invoke getMBeanServerConnection() on them to retrieve different connections? Or, do I need to make this method synchronized (and reduce efficiency)?

+1  A: 

I think the short answer is that you need to use synchronization and take the performance hit.

Given that JMX calls are RMI/network based, a synchronized block would be very cheap in comparison. Any solution that you implement that has a usage counter would suffer from race conditions -- especially considering that JMXConnector most likely has no protection against close/connect race conditions. For example, someone could be closing the connection at the same time someone else was connecting and the new connection might be closed.

I think you should write a wrapper class (or method) to the connector. It would:

  • Have a connect method that would call connect() (only if the usage-counter was 0), call getMBeanServerConnection(), and increment the usage-counter and return the connection.
  • Have a close method that would decrement the usage-counter and call close if it is 0.
  • Be synchronized to avoid the race conditions.

Best of luck.

Gray