简体   繁体   中英

Is it possible that a write in a Java socket throw without a simultaneous read throwing?

Let's says I have two threads, one for reading and one for sending; if a write fails, will the read operation in the other thread always fail too?

I think there is at least one case where this will not be the case (InterruptedIOException if sending thread is interrupted), but is there any other? If so, are some of those cases related to network problem?

Another way is if you have shutdown your socket for writing. You can't write but you can still read.

When a Socket is closed at the other end, you can fail to write (as the data has no where to go) but there might be unread data which you should still be able to read.

If you get a timeout on the read, you may want to close socket and kill any write. eg if the other end has locked up. If you don't do this the writing thread could block forever waiting to write a socket which has timed out (and may be forever)

I suppose it really depends on your situation. Probably the most common situation is your connection closing, meaning both reading and writing would fail. However, it's not necessarily true. You may have some weird firewall setting which allows you to read but not write.

My advice to you is to program each thread separtely rather than think up every possible scenario. If you try to read and you can't, what happens? If you try to write in the other thread and can't, what happens? If it's so important that both threads can read and write, design some fallback mechanism that stops the other thread if the current thread is having trouble in some way (and if the other thread is still active of course).

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