xxxDispatcher not marking FileDescriptors as invalid

Alan Bateman Alan.Bateman at oracle.com
Fri Jan 27 17:15:54 UTC 2023


On 27/01/2023 16:05, Radim Vansa wrote:
> Hello,
>
> I was experimenting with tracking file descriptors for checkpoint & restore [1] and found that in some cases, using FileDispatcherImpl/UnixDispatcher (depending on JDK version) the java.io.FileDescriptor is not closed properly. While the underlying descriptor is closed the `fd` field in the FileDescriptor object is not set [2] to -1 like the regular FileDescriptor.close0() method would do [3].
>
> Is there any special idea behind that, or is this alternate code path present only as an optimization in case where we know that none of the regular handling would be needed? Is there any risk in unsetting the fd field?

In the java.io APIs, FIS/FOS/RAF define getFD methods so the 
FileDescriptor can be obtained by applications. This is problematic for 
a bunch of reasons but for the discussion here, setting it to -1 is 
needed for the FileDescriptor::valid. Another point is that java.io 
pre-dates the more robust async close mechanism that is NIO and setting 
it to -1 helps avoid trying to use a file descriptor that has been 
closed and/or recycled.

In the NIO area, FileDescriptor objects do not leak to applications. The 
only case where it is necessary to set to -1 is on Windows with sockets 
and this is because there is no equivalent of dup2 there. Another point 
here is that FileDescriptors aren't really needed as the channels 
implementation just need the raw file descriptor or handle.

-Alan


More information about the nio-dev mailing list