DeepNightTwo
DeepNightTwo

Reputation: 4951

How to flush a SocketChannel in 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...

Upvotes: 7

Views: 10432

Answers (3)

datalost
datalost

Reputation: 3773

Use either .force() or .getFD.sync()

Update: Since you updated your question to be more specific on a SocketChannel (it was generally NIO), please see my reply instead.

Upvotes: 0

user207421
user207421

Reputation: 310998

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.

Upvotes: 13

Peter Lawrey
Peter Lawrey

Reputation: 533620

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.

Upvotes: 4

Related Questions