AsynchronousFileChannel.finalize()?

Zhong Yu zhong.j.yu at gmail.com
Wed Mar 28 19:40:59 PDT 2012


You are right, we can't wait till GC to close a file; user code has to
trigger close() asap.

In the use case, how much overhead can we really save by using a
shared channel? If instead a new channel is opened for every new
request, the added overhead won't be significant, considering OS
caching, correct? If there's not much advantage to share a channel, my
use case can be simply dismissed.

Zhong Yu

On Wed, Mar 28, 2012 at 7:16 PM, Vitaly Davidovich <vitalyd at gmail.com> wrote:
> Relying on finalization is far from ideal given its nondeterminism.  It
> seems like you may want to have a ref count associated with the channel,
> which is checked during eviction.  This will require some bookkeeping and
> maybe locking in a few places, which may reduce throughput somewhat, but at
> least you'll have full control and deterministic behavior.  Just a thought
> ...
>
> Sent from my phone
>
> On Mar 28, 2012 7:36 PM, "Zhong Yu" <zhong.j.yu at gmail.com> wrote:
>>
>> 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
>> sun.misc.Cleaner)?
>>
>> 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.)
>>
>> Zhong Yu


More information about the nio-dev mailing list