zhong.j.yu at gmail.com
Wed Mar 28 16:34:45 PDT 2012
It appears that if close() is not invoked before an
AsynchronousFileChannel becomes unreachable, the file handle remains
open, and we get a resource leak.
We can blame the programer for not properly closing the channel.
However, would the nio team consider to add a feature anyway that will
automatically invoke close() in finalize() (or something like
I have a use case where this feature could be helpful. A server has a
file that's constantly requested by clients. The server opens one
AsynchronousFileChannel and caches it. The same channel is used to
serve all client requests to the file. When the server evicts the
channel from the cache, it cannot immediately close() the channel
right away, because the channel could still be referenced by request
processors reading the file. The channel should be closed only after
nobody references it.
The point is that an AsynchronousFileChannel can be shared and
accessed concurrently by multiple users; then it is difficult to
pre-assign a user with the responsibility of closing the channel. It
should be the last user that uses the channel - which is better
handled in JDK.
(In comparison, FileInputStream/FileChannel should have only one user
at any given time, therefore it's clear who is responsible to do the
close(). I wouldn't request the feature on these two classes.)
More information about the nio-dev