Write contents of an InputStream (blocking) to a non-blocking socket
I'm programming a simple Java NIO server and have a little headache: I get normal InputStream
s i need to pipe to my clients. I have a single thread performing all writes, so this creates a problem: if the InputStream
blocks, all other connection writing will be paused.
I can use InputStream.available()
to check if there are any incoming data I can read without blocking, but if I've reached end-of-stream it seems I must call read()
to know.
This creates a major headache for me, but I can't possibly believe I'm the first to have this problem.
The only options I've come up with so far:
- Have a separate thread for each
InputStream
, however that's just silly since I'm using non-blocking I/开发者_如何学PythonO in the first place. I could also have a thread pool doing this but then again that limits the amount of simultaneous clients I can pipe theInputStream
to. - Have a separate thread reading these streams with a timeout (using another thread to interrupt if reading has lasted longer than a certain amount of time), but that'll most certainly choke the data flow should I have many open
InputStream
s not delivering data.
Of course, if there was a magic InputStream.isEof()
or isClosed()
then this wouldn't be any problem at all :'(
".....Have a separate thread for each InputStream, however that's just silly since I'm using non-blocking I/O in the first place...."
It's not silly at all. First you need to check whether you can retrieve a SelectableChannel from your InputStream implementation. If it does you are lucky and you can just register it with a selector and do as usual. But chances are that your InputStream may have a channel that's not a SelectableChannel, in which case "Have a separate thread for each InputStream" is the obvious thing to do and probably the right thing to do.
Note that there is a similar problem discussed in SO about not able to get a SelectableChannel from an inputstream. Unfortunately you are stuck.
I have a single thread performing all writes
Have you stopped to consider whether that is part of the problem rather than part of the solution?
精彩评论