简体   繁体   中英

Atomic non-blocking writes to stream sockets

If I write(byte[]) to an OutputStream obtained from Socket.getOutputStream() on a non-blocking Socket backed by a Channel , and write() throws IllegalBlockingModeException , is it guaranteed that all the byte-array is written or none of it is?

I can't find a clear answer in the docs linked above.

See the Javadoc of Channels.newOutputStream():

The write methods of the resulting stream will throw an IllegalBlockingModeException if invoked while the underlying channel is in non-blocking mode.

The mode is checked before any write is attempted. No other implementation would make sense. And if writing was possible why would there be an exception at all?

Short answer: Don't assume either or and do not require any specific behavior for the correct function of your code.

Long answer: There is no way to generically tell for sure; if an IOException is thrown, it can occur at any point of the operation and the state of the stream should be assumed as "undefined" afterwards.

Despite the javadoc of IllegalBlockingException stating

Unchecked exception thrown when a blocking-mode-specific operation
is invoked upon a channel in the incorrect blocking mode

and while the wording implies that it is checked before any work actually takes place (it wouldn't make sense to check for an illegal operation after actually performing it), the problem is the exception is probably occuring somewhere in a set of related objects, so there is no way of knowing if any of these objects states has changed before the exception was thrown.

The sanest option is to not attempt the operation, or if it can't be avoided, not to assume anything in particular about the state of the stream/channel after the exception occured.

I would however assume hat no bytes will have been actually written, because the condition makes only sense to check before actually writing data - but - thats actually an implementation detail in SocketChannelImpl. You could dig for the source code of sun.nio.ch.SocketChannelImpl (its not provided in src.zip) to actually check the implementation; but that would only give definite proof for that specific implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM