为什么不在每次定期调用sendMessage()之前初始化TcpSyslogMessageSender呢?

huangapple go评论76阅读模式
英文:

Why not initializing a TcpSyslogMessageSender before every periodic sendMessage()?

问题

我在一个简单的应用程序中使用CloudBees Syslog Java Client来周期性地向服务器发送Syslog消息。一切都正常,但我想知道 - 如果在每个循环中初始化TcpSyslogMessageSender类,那么在经过10次迭代后,它将停止发送新消息而不会引发任何异常。我可以很容易地将其更改,并将对象初始化移动到调用类的构造函数中,但我想理解其中的原因。从我的角度来看,我在每次迭代时都初始化了一个全新的对象。垃圾收集器应该会删除旧对象并释放已使用的网络资源。但也许情况没有那么简单。 为什么不在每次定期调用sendMessage()之前初始化TcpSyslogMessageSender呢?

while(true){
    TcpSyslogMessageSender messageSender = new TcpSyslogMessageSender();
    messageSender.setDefaultMessageHostname(...);
    ...
    messageSender.sendMessage(msg);
}

希望能够了解这个问题!

祝好,

cmax

英文:

I am using CloudBees Syslog Java Client in a simple application to send Syslog messages periodically to an server. All works fine but I wondered - if the TcpSyslogMessageSender-Class is initialized on every loop, it will stop sending new messages after 10 iterations without any exception. I can easily change this and move the object initialization to the constructor of the calling class, but I want to understand why this is. From my point of view I am initializing a clean new object on every iteration. The Garbage Collection should remove the older objects and free the used network resources. But maybe it is not that easy. 为什么不在每次定期调用sendMessage()之前初始化TcpSyslogMessageSender呢?

while(true){
            TcpSyslogMessageSender messageSender = new TcpSyslogMessageSender();
            messageSender.setDefaultMessageHostname(...);
            ...
            messageSender.sendMessage(msg);
}

Would like to learn about it!

Cheers,

cmax

答案1

得分: 0

我正在回答自己:我了解到TcpSyslogMessageSender有一个close方法,该方法实际上会关闭已使用的套接字。似乎不可能从一个Java实例中并行打开超过10个套接字。不幸的是,关闭调用不是提供的代码示例的一部分。现在,对于多次初始化和重新初始化TcpSyslogMessageSender来说绝对没有问题。希望有人会发现这对他们有帮助。

英文:

I am answering to myself: I learned that TcpSyslogMessageSender has a close-method which actually closes the used socket. It seems that it was not possible to open more that 10 sockets from one Java-instance in parallel. Unfortunately, the close-call was not part of the given code example. Now, it is absolutely no problem to initialize and reinitialize the TcpSyslogMessageSender for many times. Hope someone will find this helpful.

huangapple
  • 本文由 发表于 2020年10月13日 12:36:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64328596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定