FTP连接性能java



我想通过打开一次FTP连接来优化性能。这可能吗?

我正在做

public void method1()
{
  for(loop)
  {
    List li = someList;
    method2(li); //Here I am calling this method in loop. This method has code for FTP connection. So for every iteration it is opening FTP connection in method2().
  }
}
public void method2(List li)
{
 open FTP connection // FTP connect code here
 once FTP connection obtained ....do some other stuff...
}

谢谢。

您没有向我们解释您想要做什么优化。是否要重用连接?不可能以多线程的方式使用连接(想象一下在文件传输时发送流命令:这是不可能的)。

唯一的优化是保持两组命令之间的连接打开(可以避免关闭和重新打开连接的成本,这是非常昂贵的)。

对于静态的东西要非常小心:在多线程环境中(例如应用程序服务器)通常会出现问题。

您可以使用一个静态(或者实际上是实例)变量,它是这样创建的;

private static FTPConnection myFTPCon = openFTPConnection();
private static FTPConnection openFTPConnection()
{
    //open ftp connection here and return it
}
public void method1()
{
    for(loop)
    {
        List li = someList;
        method2(li);
    }
}
public synchronized void method2(List li)
{
     //use myFTPCon here
}

编辑以回应评论

public class MyFTPClass {
    private FTPConnection myFTPCon;
    public MyFTPClass(String host, String user, String password) {
        //connect to the ftp server and assign a value to myFTPCon
    }
    public synchronized void method() {
        //use the myFTPCon object here
    }
}

然后,您将从主程序流中构造一个MyFTPClass对象,并从那里使用它。每个新的MyFTPClass实例都指向不同的FTP服务器连接,因此您可以根据需要拥有任意数量的连接。

最新更新