Apache Commons NET: Should I create a new FTPClient object on each connection or reuse one?
Asked Answered
B

3

9

I'm just wondering: in my Java application, each time I need to connect to an FTP server, should I create a new FTPClient object, or should I create one FTPClient() object and re-use that each time I connect to an FTP server?

Boot answered 31/7, 2011 at 20:20 Comment(0)
O
3

Reusing would be better since you wont need a new instance every time you are creating a new connection, even to a new server. Because the connect and disconnect methods can do the job for you.

So reuse as many objects as you can.

Ohara answered 31/7, 2011 at 20:29 Comment(4)
Thank you, was just making sure :)Boot
However, if you want to make simultaneous connections you'd probably need multiple instances.Ohara
Do you have any data on the cost of creating a new instance, or is this just a guess?Sharpen
Thanks, but I only need to connect to one FTP at a time :)Boot
P
17

Both will work, but apache commons.net libraries are not thread safe, so if you do use one client with multiple threads, be aware that you'll have to synchronize access to it.

Pullen answered 31/7, 2011 at 22:43 Comment(0)
B
4

Without knowing exactly what your code has to do (how often it connects, how many files it needs to transfer etc) it's difficult to say.

My personal opinion would be one FTPClient() but connect/authenticate/transfer/disconnect each time you need to do something (assuming there will be a reasonable gap in between). The reasoning is that FTP sessions often have fairly short inactivity time-outs.

Bawdy answered 31/7, 2011 at 20:31 Comment(0)
O
3

Reusing would be better since you wont need a new instance every time you are creating a new connection, even to a new server. Because the connect and disconnect methods can do the job for you.

So reuse as many objects as you can.

Ohara answered 31/7, 2011 at 20:29 Comment(4)
Thank you, was just making sure :)Boot
However, if you want to make simultaneous connections you'd probably need multiple instances.Ohara
Do you have any data on the cost of creating a new instance, or is this just a guess?Sharpen
Thanks, but I only need to connect to one FTP at a time :)Boot

© 2022 - 2024 — McMap. All rights reserved.