0

Running into an issue where connection.start() fails due to

java.net.ConnectException: Connection refused: connect

when I wrap my javax.jms.TopicConnection in a ThreadLocal, as follows:

private ThreadLocal<TopicConnection> createThreadLocalTopicConnection(final TopicConnectionFactory cf)
{
    return new ThreadLocal<TopicConnection>() {
        public TopicConnection result;

        protected synchronized TopicConnection initialValue() {
            try {
                // Returns a javax.jms.TopicConnection object.
                result = cf.createTopicConnection();
                result.start();
                return result;
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }
        }

            protected void finalize() throws Throwable {
                if(result!=null) result.close();
            }
        };
    }

If I just create the TopicConnection as a bare static variable, it connects without any issues. Can anybody explain why it would work as a bare variable but when wrapped in a ThreadLocal it would fail? Google has failed me pretty spectacularly this time around.

StormeHawke
  • 5,987
  • 5
  • 45
  • 73

2 Answers2

0

It's hard to say exactly why this is happening, but JMS clients are usually multi-threaded beasts, so I can see that this strategy might not be totally kosher.

JMS Connections are intended to be thread-safe, you you might want to just wrap your connection in a singleton or something. (JMS Sessions and below are not thread-safe and should not be shared by threads, so you might consider putting the session in a thread local if you're committed to this approach).

Nicholas
  • 15,916
  • 4
  • 42
  • 66
  • The reason I wrapped it in a ThreadLocal is because when I simply declared the connection as static I was getting some odd side-effect behavior where intra-app messages weren't being received while inter-app messages were working as expected. I am suspecting that some inter-thread configuration differences are the culprit. Working with ActiveMQ's PooledConnectionFactory resolves the issue, but I'm trying to avoid stepping outside of the javax.jms references already in my code – StormeHawke Jul 26 '13 at 17:44
0

ThreadLocal would mean every Thread is getting it's own Connection. Do compare how many threads the application is spawning vs the number of connections in the ActivationSpec

user1132593
  • 448
  • 1
  • 5
  • 8
  • "ThreadLocal would mean every Thread is getting it's own Connection". That was kind of the point. Thanks though – StormeHawke Jul 26 '13 at 21:08