How to make an InputStream time out?

N

NKV

E.g. while reading from a URL I would like to timeout after a certain
time (say timeOutMS). I was thinking of embedding the read operation
in a thread (say t) and then use t.join(timeOutMS). But this way I
necessarily have to use a thread. Any other solutions?
 
K

Knute Johnson

NKV said:
E.g. while reading from a URL I would like to timeout after a certain
time (say timeOutMS). I was thinking of embedding the read operation
in a thread (say t) and then use t.join(timeOutMS). But this way I
necessarily have to use a thread. Any other solutions?

I assume you are connecting to an HTTP server? Take a look at the docs
for 1.5, it has some new features, one of which is timeouts for HTTP
connections. If you don't want to use 1.5, make yourself an alligator.
When you make your connection, also start a timer. When the timer
runs out it can close the InputStream. You can reset the timer if data
is still coming in if you want.
 
F

Frank

E.g. while reading from a URL I would like to timeout after a certain
time (say timeOutMS). I was thinking of embedding the read operation
in a thread (say t) and then use t.join(timeOutMS). But this way I
necessarily have to use a thread. Any other solutions?


It sounds like Knute's idea for closing the stream is the most probably
candidate. However, if you can get a hold of the actual Socket being used,
you can attempt to call setSoTimeout. Otherwise, you might also want to
try using another thread to call Thread.interrupt() on your blocked
(reading) thread... if your InputStream there is "nice" it may throw an
InterruptedIOException

Hope this helps,

Frank
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top