RFR: 8278326: Socket close is not thread safe and other cleanup
Alan Bateman
alanb at openjdk.org
Tue Jan 10 14:09:56 UTC 2023
On Tue, 10 Jan 2023 14:01:31 GMT, Jaikiran Pai <jpai at openjdk.org> wrote:
>> java.net.Socket is not specified to be thread safe but it is required to support async close. If you create an unbound Socket and close it at around the time that another thread is binding, connecting, or anything else that creates the underlying socket then it can leak. The simplest thing to do is to synchronize all methods but the underlying SocketImpl implementation is thread safe, and all we really need is for Socket (and ServerSocket) to synchronize the creation of the underlying socket (SocketImpl.create) with close. As part of this change I've replaced the 6 flags with a bit mask. A new test is added to the Socket/asyncClose directory to test closing concurrently with another operation, the test will detect if the closed Socket is connected to a SocketImpl with an open socket.
>>
>> Related is that ServerSocket.implAccept can be overridden to provide the Socket to accept. Its behavior is unspecified when called with a Socket that isn't newly created/unbound and there are number of silly scenarios that can arise. I've changed implAccept to coordinate with close so that accept doesn't return a closed Socket that is connected to an underlying socket. A new test is added to exercise these scenarios.
>>
>> There are a couple of random cleanup/formatting nits in this patch.
>
> src/java.base/share/classes/java/net/Socket.java line 633:
>
>> 631: SocketImpl previous = impl;
>> 632: impl = si;
>> 633: state = (SOCKET_CREATED | BOUND | CONNECTED);
>
> Could we replace this line with `setConnected()` (which does the same thing as what's being done here)? The reason I say that is because it becomes a bit easier, in a IDE, to see who all calls `setConnected()` and that helps understand which all places in the code trigger this state change. Given the context of this code, I suspect it wouldn't be any noticable impact on performance.
> This is mostly a nit and you can ignore it if you prefer to keep it in the current form.
In setConnectedImpl it needs to be very clear which state bits are set so I think I'd prefer to leave that as is.
-------------
PR: https://git.openjdk.org/jdk/pull/11863
More information about the net-dev
mailing list