RFR 8080225 FileInput/OutputStream/FileChannel cleanup should be improved

Peter Levart peter.levart at gmail.com
Mon Dec 4 14:25:28 UTC 2017

Hi Roger,

On 12/04/2017 03:09 PM, Peter Levart wrote:
> On 12/04/2017 02:25 PM, Peter Levart wrote:
>> Hi Rogger,
>> On 12/04/2017 02:17 PM, Peter Levart wrote:
>>> Hi Rogger,
>>> Interesting approach. Conditional finalization. You use finalization 
>>> to support cases where user overrides finalize() and/or close() and 
>>> Cleaner when he doesn't.
>>> I wonder if it is the right thing to use AltFinalizer when user 
>>> overrides finalize() method. In that case the method is probably not 
>>> empty and calls super.finalize() (if it is empty or doesn't call 
>>> super, user probably doesn't want the finalization to close the 
>>> stream) and so normal finalization applies. If you register 
>>> AltFinalizer for such case, close() will be called twice.
>> Ah, scrap that. I forgot that XXXStream.finalize() is now empty, so 
>> user overriding it and calling super does not in fact close the 
>> stream. You have to register AltFinalizer in that case. But now I 
>> wonder if the logic should still be 3-state and do the following:
>> - if user overrides finalize() - use AltFinalizer to call both: first 
>> finalize() and then close(); else
>> - if user overrides close() - use AltFinalizer to call close(); else
>> - use Cleaner
>> What do you think?
>> Regards, Peter
> I just realized that in the above case when finalize is overridden, it 
> would be called twice. once by finalization and once by AltFinalizer. 
> So your logic is as correct as it can be for that case (to just call 
> close() with AltFinalizer). The only problem is order which is 
> arbitrary, so it may happen that AltFinalizer calls close() 1st and 
> then finalization calls overridden finalize() method which might 
> expect the stream to still be open until it calls super.finalize().
> Regards, Peter

Final refinement... (hopefully!)

If user overrides just finalize() and does not override close(), then it 
might be best to employ Cleaner to close the stream. Cleaner is Phantom 
based and will get fired after finalization invokes overridden 
finalize(), enabling the finalize() method to still access the stream in 
that case. So this is the final logic (I think):

- if user overrides close(), use AltFinalizer to call close(); else
- use Cleaner to close the stream

The above logic in action:

finalize()              close()                        action

not overridden    not overridden           Cleaner closes stream
not overridden    overridden                 AltFinalizer calls close()
overridden          not overridden           finalization calls 
finalize() then Cleaner closes stream
overridden          overridden                 finalization calls 
finalize() and AltFinalizer calls close() (in arbitrary order)

Regards, Peter

More information about the core-libs-dev mailing list