Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flush a SocketChannel in Java NIO?

Tags:

java

nio

In Java IO, an OutputStream can use flush() method to make sure data is sent at once.

Is there a corresponding function in Java NIO for SocketChannel? As far as I know, there is a force() method for FileChannel to flush data.

Might be a very naive question...

like image 371
DeepNightTwo Avatar asked Sep 16 '11 05:09

DeepNightTwo


2 Answers

OutputStream.flush() does nothing except flush the buffers of any BufferedOutputStreams or ObjectOutputStreams or PrintStreams that are in the stack.

Specifically, it doesn't do anything corresponding to FileChannel.force() or getFD().sync(). It just flushes stream buffers from the JVM into (in this case) the socket send buffer in the kernel.

SocketChannel.write() doesn't involve any such buffering at all: it goes directly to the socket send buffer in the kernel. So there is nothing to flush, so there is no flush operation.

like image 137
user207421 Avatar answered Oct 19 '22 18:10

user207421


When you force() the data to disk, the OS can determine it has been written to disk successfully. However TCP communication is more complex and the data passes through many stages outside the OSes control. Generally speaking, the OS wills end out the data as soon as possible and won't buffer the socket data (typically about 64 KB) to the degree it will buffer disk writes (sometimes GBs)

The best way to ensure the data has been received successfully is to have the other end send a response.

If you want data to be sent as fast as possible you can try turning nagle off, however most OSes are pretty smart at optimising this and turning it off doesn't make as much difference as it used.

like image 37
Peter Lawrey Avatar answered Oct 19 '22 19:10

Peter Lawrey