Is an OutputStream in Java blocking? (Sockets)

salbeira picture salbeira · May 13, 2012 · Viewed 20.2k times · Source

I am currently writing naive network code for a project and a mate hinted me at the possibility that when I send a package of information from the server to all clients in an iterative fashion I might get intense lag when one of the clients is not responding properly.

He is reknown for trolling so I was kind of sceptical when implementing a secondary thread that is now responsible to send data over to a client, having a queue that the Server simply adds the packages over that is then read by the thread to send data.

The question I now have after thinking it over is weather or not the OutputStream of a Java Socket actually queues the stuff he wants to send by itself, thus eliminating the need of a queue beforehand. The possibility of having intense problems occurrs only when the Server is blocking as long as he does not get a response from a client that the sent object was recieved.

Thanks.

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · May 13, 2012

Your friend is right but it has more to do with how protocol works. Largely simplifying packets sent to the client need to be confirmed. If the client is not responding (fails to read incoming data, computer is under heavy load, etc.) the server won't receive acknowledgements and will stop sending the data. This mechanism built into TCP/IP prevents one end of the communication from sending large amounts of data without making sure the other end received them. In turns this avoid the requirement to resend big amounts of data.

In Java this manifests as blocking write to OutputStream. The underlying TCP/IP stack/operating system does not allow sending more data until the client is ready to receive it.

You can easily test this! I implemented simple server that accepts connection but fails to read incoming data:

new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            final ServerSocket serverSocket = new ServerSocket(4444);
            final Socket clientSocket = serverSocket.accept();
            final InputStream inputStream = clientSocket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}).start();

And a simple client that just sends as much data as it can in 4K batches:

final Socket client = new Socket("localhost", 4444);
final OutputStream outputStream = client.getOutputStream();
int packet = 0;
while(true) {
    System.out.println(++packet);
    outputStream.write(new byte[1024 * 4]);
}

The client loop hangs on my computer after 95 iterations (your mileage may vary). However if I read from inputStream in server thread - the loop goes on and on.