I've written a little app in java that writes a few lines to a text file every ten seconds or so. Is is better to initialise the input stream outside the loop and keep it open for a very long time, or to open and close it every time I need to use it?
I don't think it really matters in this example, since it's such a slow loop, but I'd like to know just for future referance. What about an identical scenario but pertaining to a JDBC connection?..
Many thanks.
For a file stream, I think I'd keep the stream open. If you are forever opening and closing it, there is always a remote possibility that an open might fail because someone has opened / locked the file in an editor since you last wrote to it. (Besides, the system calls to open and close a file don't come for free ...)
For the JDBC case, you should do neither. Rather you should use a JDBC connection pool, and let that take care of opening / closing the connection. (One issue with hanging onto a database connection for a long time is that the database can close it. Depending on your JDBC driver, this can cause problems when you try to use the closed connection.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With