Search code examples
javamultithreadingconnection-poolingsftpjsch

Using connection pool with JSch


I'm using JSch for file upload over SFTP. In its current state each thread opens and closes connection when needed.

If it possible to use connection pooling with JSch in order to avoid overhead caused by large number of connection opening and closing?

Here is a example of function called from inside of thread

 public static void file_upload(String filename) throws IOException {
    JSch jsch = new JSch();
    Session session = null;
    try {
        session = jsch.getSession("user", "server_name", 22);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword("super_secre_password");
        session.connect();

        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp sftpChannel = (ChannelSftp) channel;
             
        FileInputStream inputSrr = new FileInputStream(filename);  
        try {  
            sftpChannel.put(inputSrr, "/var/temp/"+filename);  
        } catch (SftpException e) {  
            e.printStackTrace();  

        } finally {  
            if (inputSrr != null) {  
                inputSrr.close();  
            }  
        }  
        
        sftpChannel.exit();
        session.disconnect();
    } catch (JSchException e) {
        e.printStackTrace();
    } catch (SftpException e) {
        e.printStackTrace();
    }
}

Solution

  • For that I would prefer commons-pool. ;)