如果我从多个线程中使用JSch,应该如何使用它 [英] If I use JSch from more than one thread, how should I use it

查看:714
本文介绍了如果我从多个线程中使用JSch,应该如何使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于连接创建需要花费很多时间,并且我想连接到多个主机,所以我开始从多个线程使用JSch。

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.

但是我收到一些令人讨厌的异常,我认为这是因为JSch不是线程安全的。我应该如何使用它,以免由于JSch的非线程安全性而引发任何异常?

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:

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.

推荐答案

与其他任何非线程安全类一样。

As any other non-thread safe class.

一次只能从单个线程访问它。

Access it from a single thread at a time only.

使用 synchronized 语句:< br>
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).

这篇关于如果我从多个线程中使用JSch,应该如何使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆