Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : Is ServerSocket.accept threadsafe?

For a project in school, we are making a multithreaded server in Java 5.0. This project is centered on the concurrence aspect of a server.

We have some threads dedicated to treating the requests. To do so, they have a call to a ServerSocket.accept() to accept new connections. Our choice was to start a bunch of them and let them treat the incoming connections with the assumption that two threads cannot accept() the same connection at the same time.

But now the main problem is that we cannot find anything in the API that guaranty us this behavior (or we didn't look right) and we have nothing except the "it works" proof.

Has someone a source to look for this sort of information on the java methods ?

like image 350
Thomas Schwery Avatar asked May 22 '09 07:05

Thomas Schwery


1 Answers

This does not quite answer your question, but running accept() on multiple threads sounds like there is something wrong with the design of the server.

Usually there should be no need to run accept() from multiple threads.

Your code should looks something like this:

while (serverIsUpAndRunning())
{
    // Wait for an incoming connection.
    Socket s = serverSocket.accept();
    // Spawn a thread to handle the socket,
    // so that we don't block new connections.
    SocketHandlerThread t = new SocketHandlerThread(s);
    t.start();
}
like image 134
Nuoji Avatar answered Oct 25 '22 00:10

Nuoji