Arne
Arne

Reputation: 3064

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 InputStreams 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:

Of course, if there was a magic InputStream.isEof() or isClosed() then this wouldn't be any problem at all :'(

Upvotes: 3

Views: 1097

Answers (2)

user207421
user207421

Reputation: 310860

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?

Upvotes: -1

Suraj Chandran
Suraj Chandran

Reputation: 24791

".....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.

Upvotes: 3

Related Questions