If I use JSch from more than one thread, how should I use it

南笙酒味 提交于 2020-08-19 06:43:42

问题


Since connection creation takes up quite a few times, and I'd like to connect to multiple hosts, I started to use JSch from multiple threads.

However I get some nasty exceptions, which I think is because of JSch being not thread-safe. How should I use it, that it not throws any exception, which is due to the not-thread-safety of JSch?

Stacktrace:

com.jcraft.jsch.JSchException: connection is closed by foreign host
    at com.jcraft.jsch.Session.connect(Session.java:269)
    at com.jcraft.jsch.Session.connect(Session.java:183)
    at com.ericsson.eea.ark.test.common.ssh.JschSshContext.session$lzycompute(JschSshContext.scala:64)

update

In my test I connected to the same host multiple times. That's why I got the exception.


回答1:


As any other non-thread safe class.

Access it from a single thread at a time only.

Use synchronized statement:
https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html

If this downgrades performance, you can create a connection pool.


Though I do not think this exception is caused by a concurrent access.

It's rather that the server rejects too frequent connection attempts from the same host (what is quite common).




回答2:


Just to complement @Martin Prikryl answer that actually solved my problem.

In my case it was the server that didn't allow more than 20 simultaneous connections. After spending 4 hours, I finally talked to the infrastructure team and they increased the maximum SSH connections on the Linux server to 50.

For the record, the steps are (you'll need root access on the server):

  1. Edit the /etc/ssh/sshd_config file and set the MaxSessions parameter to 50 connections (in my case).

  2. In the same file set the MaxStartups parameter to 50/30/50.

  3. Restart the SSH service (or restart the whole box).



来源:https://stackoverflow.com/questions/38915200/if-i-use-jsch-from-more-than-one-thread-how-should-i-use-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!