Search code examples
javaserversocket

Where exactly does a thread hang in a ServerSocket.accept() during waiting for a connection?


In the block below, I understand that this main thread is blocking and is therefore not listening for interruptions from other threads but does that mean that it literally hangs on the ServerSocket.accept() line?

        ServerSocket serverSocket = new ServerSocket(8080);

        while(true){ // Block until accept
            Socket acceptedSocket = serverSocket.accept(); // Give accepted socket OR NULL SOCKET to acceptedSocket

            handle(acceptedSocket);

            serverSocket.close();
        }

I am asking because I can't understand where it would be getting hanged up on the accept (ServerSocket.java):

public Socket accept() throws IOException {
        if (isClosed()) // No its open
            throw new SocketException("Socket is closed");
        if (!isBound())   // No its bound to 8080
            throw new SocketException("Socket is not bound yet");
        Socket s = new Socket((SocketImpl) null);                  // Create a null socket
        implAccept(s);                                          // Here???
        return s;
    }

ServerSocket.java again:

protected final void implAccept(Socket s) throws IOException {


  SocketImpl si = null;
    try {
        if (s.impl == null)
          s.setImpl();
        else {
            s.impl.reset();
        }
        si = s.impl;
        s.impl = null;
        si.address = new InetAddress();
        si.fd = new FileDescriptor();
        getImpl().accept(si);    // I'm thinking its here but when I look at this accept, thats an abstract method and don't know where to dig deeper.

Solution

  • Depends on the OS, but on Linux, accept() is a kernel call. The most straighforward Java implementation would be to use that kernel call.

    So the process is 'waiting in the kernel', loosely speaking.