Short answer: if the documentation does not specify that something is thread safe, then you must assume that it is not. You need to do the coordination between threads yourself to make sure that no two threads use the server socket at the same time.
This is especially important because some other code could have registered its own socket implementation with ServerSocket.setSocketFactory
. Even if the default socket implementation is thread-safe, custom implementations don't have to be. There is nothing in the documentation that says so.
Long answer: the Default Windows Implementation
You can download and inspect the java SE 1.6 source code.
I started at \j2se\src\share\classes\java\net\ServerSocket.java
and from there the trail led to PlainSocketImpl.java
. The PlainSocketImpl.Accept
method is marked as native
.
The native C++ code for windows is in \j2se\src\windows\native\java\net\PlainSocketImpl.c
. It uses the winsock accept function. From an MSDN article on WinSock (emphasis mine):
Under Windows NT and Windows 2000,
Windows Sockets support for 16-bit
applications is based on WINSOCK.DLL.
For 32-bit applications, the support
is in WSOCK32.DLL. The APIs provided
are identical except that the 32-bit
versions have parameters widened to 32
bits. Under Win32, thread safety is
supplied.
So at least on windows, Socket.Accept
is thread safe in the sense that it will not let two threads accept the same connection. There also is infrastructure in the ServerSocket
implementation (e.g. the Close() method uses a lock) which indicates that it is intended to be thread safe.