Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Re: Timeout for InputStream

Thread Tools

Re: Timeout for InputStream

Filip Larsen
Posts: n/a
Manish Hatwalne wrote

> Is it possible somehow to get an input stream from an

> object to timeout on a read() operation? How can I do it?

Recently I had to do the same in a way that did not require major change
to an existing input stream pipeline, and I came up with the
PolledInputStream class included below. You may be able to modify it to
suit your needs.

Note: to work it relies on the underlying inputstream being able to
report available() > 0 when there is input, which do not necessarily
hold for all InputStreams. However, it do seem to hold for Sun's
HttpURLConnection input streams as far as I have been able to test.


* Adapter to change blocking input into polled input with timeout.
* @author Filip Larsen
public class PolledInputStream extends InputStream {

public PolledInputStream(InputStream input, long timeout) {
this.input = input;
this.timeout = timeout;

public int available() throws IOException {
return input.available();

public void close() throws IOException {

public void mark(int readlimit) {

public boolean markSupported() {
return input.markSupported();

public int read() throws IOException {

public int read(byte[] b) throws IOException {
return read(b,0,b.length);

public int read(byte[] b, int off, int len) throws IOException {
int n = available();
return, off, Math.min(len,n));

public void reset() throws IOException {

public long skip(long n) throws IOException {
return input.skip(n);

private InputStream input;
private long timeout;

private void sleep(long time) {
try {
} catch (InterruptedException ignore) {

private void waitForAvailable() throws IOException {
long until = System.currentTimeMillis() + timeout;
while (available() == 0) {
if (System.currentTimeMillis() > until) {
throw new IOException("input timed out");
try {
} catch (InterruptedException ignore) {


====End of

Filip Larsen

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Need an InputStream with Timeout (or equivalent) Knute Johnson Java 7 08-18-2009 09:15 PM
HttpRequest InputStream read timeout Java 0 03-15-2007 09:24 PM
confused: Socket InputStream != ServerSocker InputStream R Java 5 03-13-2005 07:26 AM
Timeout::timeout and Socket timeout Mark Probert Ruby 1 10-06-2004 09:30 AM
Re: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. Bob Johnson ASP .Net 0 08-07-2003 12:52 PM