[英]Connection Refused when wrapping JMS Connection in ThreadLocal
Running into an issue where connection.start() fails due to 遇到由于以下原因而导致connection.start()失败的问题
java.net.ConnectException: Connection refused: connect
when I wrap my javax.jms.TopicConnection
in a ThreadLocal
, as follows: 当我将我的javax.jms.TopicConnection
包装在ThreadLocal
,如下所示:
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. 如果我只是将TopicConnection
创建为裸static
变量,则它可以毫无问题地进行连接。 Can anybody explain why it would work as a bare variable but when wrapped in a ThreadLocal
it would fail? 谁能解释为什么它可以作为裸变量工作,但是当包装在ThreadLocal
时会失败吗? Google has failed me pretty spectacularly this time around. 谷歌这次使我失败了。
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客户端通常是多线程的野兽,因此我可以看到这种策略可能并不完全符合要求。
JMS Connections are intended to be thread-safe, you you might want to just wrap your connection in a singleton or something. JMS连接旨在实现线程安全,您可能希望将连接包装为单例或其他形式。 (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). (JMS会话及其以下版本不是线程安全的,因此不应由线程共享,因此,如果您致力于此方法,则可以考虑将会话放在本地线程中)。
ThreadLocal would mean every Thread is getting it's own Connection. ThreadLocal意味着每个线程都将获得自己的连接。 Do compare how many threads the application is spawning vs the number of connections in the ActivationSpec 请比较应用程序产生的线程数与ActivationSpec中的连接数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.