How to timeout a Socket write using NIO
843790Dec 6 2007 — edited Dec 7 2007I have a network application which sometimes hangs on write operations. I want to implement a write timeout. My research uncovered three main ways to do this:
1. Spawn a writer thread and interrupt it if it takes too long
2. Register a TimerTask with a Timer to interrupt me (remembering to cancel the Task and clear interrupted when I come out of read)
3. Use NIO
The first option will not work for me because it would create way too many threads for my application. The second option is a possibility. I don't know enough about how NIO works to evaluate the third option.
I have yet to find any example code of how a write timeout is done in NIO. I read that you have to select on WRITE_OP but I'm not sure how that all works. I do know it can be tricky, which is why I'm looking for an example of how to do it right.
Does anyone have an example or psudocode on how to implement a write timeout in NIO?