Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's better practice : To keep a fileInputStream open for a long time, or open and close it a lot?

Tags:

java

file-io

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.

like image 745
Sam Avatar asked Oct 12 '22 15:10

Sam


1 Answers

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.)

like image 53
Stephen C Avatar answered Jan 01 '23 10:01

Stephen C