Java – why close () an input stream?
I have rich experience in Java programming language But I've been thinking, why close () Java io. What about InputStream or its subclasses?
Now use Java io. OutputStream refers to fileoutputstream. After writing a file, if we do not close the () output stream, the data we intend to write in the file will remain in the buffer and will not be written to the file
So you must close () an OutputStream But after I didn't close InputStream, I never had any painful experience
However, all articles on the Internet and books still say that it is always good to close any stream, which may be InputStream or OutputStream
So my question is, why close () an InputStream? People say you may face a memory leak. Don't close it So what kind of memory leak?
Solution
An InputStream is bound to a small kernel resource and a low - level file handle In addition, as long as you open the read file, the file will be locked (deleted, renamed) to some extent Let's imagine that you don't care about locked files Finally, if you need to read another file and open it with a new InputStream, the kernel will assign you a new descriptor (file stream) This will add up
This is just a @ R_ 502_ 1991 @, until the long - running program failed
The file descriptor table of the processor is limited in size Eventually, the file handle table will run out of free slots for the process Even thousands, you can still easily use them for long-running applications. At this time, your program will no longer be able to open new files or sockets
The process file descriptor table is simplified as follows:
IOHANDLE fds[2048]; // varies based on runtime,IO library,etc.
You start with three slots You have performed a denial of service on yourself