0

I use

URLConnection urlConn = theURL.openConnection();

// set connect timeout.
urlConn.setConnectTimeout(5000);

// set read timeout.
urlConn.setReadTimeout(5000);

in my application. One timeout for the connection time, on for the time until the read starts. Is there any simple way to timeout the actual data transfer process?

I have threads reading data from either very slow hosts, or the data source is very big, what leads to too long transfer times. How can I limit that time?

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
Olga
  • 1,516
  • 5
  • 17
  • 23
  • See http://stackoverflow.com/q/2733356/ – Saul Aug 15 '11 at 10:20
  • Thank you. But I think setting an overall timeout to the ThreadPool is not an option here. I dont want to cancel all running threads after x minutes. I would like to limit the execution time of a single thread. As far as I know interrupt() aswell does not always work on IO-blocked threads. – Olga Aug 15 '11 at 10:43

2 Answers2

0

You could try using the Thread.join(int) -> http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html#join(long). Then check the status of the thread once that's done. If it has not ended then terminate it and assume a timeout.

-1

As far as I understood, and I think the docs support this, readTimeout starts from when the reading of the InputStream starts - so this will time out for a long transfer.

Edit: the docs say:

A non-zero value specifies the timeout when reading from Input stream when a connection is established to a resource

this is possibly not that well written, but sounds to me as if this does indeed pertain to transfer time.

Richard H
  • 38,037
  • 37
  • 111
  • 138
  • No that timeout is for the reading of the data to start. The web server might want to do some pre-processing before sending out the data -> this timeout will protect you against that. –  Aug 15 '11 at 10:21
  • Read timeout doesn't starts when the data is transfered. A read timeout is the time between two packets of data being available. This might tipycally happen if the network connection is lost. – Vivien Barousse Aug 15 '11 at 10:21
  • @ExtremeCoder: ok I stand corrected. But the docs are very ambiguous then. – Richard H Aug 15 '11 at 10:26
  • For your edit: the doc also says "If the timeout expires before there is data available for read", which explicitely says that if data become available (ie, is received, even not in its whole), the timeout is reset. – Vivien Barousse Aug 15 '11 at 10:27
  • @Vivien - yes it does, as I said i think it's very ambiguous. – Richard H Aug 15 '11 at 10:32
  • @Vivien Barousse a read timeout isn't the interval between two packets. It is the maximum time spent in a single invocation of a read() method without data becoming available. It starts when you invoke read(), not from the previous packet. – user207421 Aug 16 '11 at 00:13
  • @EJP - what is your source for that? I couldn't tell that from the Javadoc. – matt freake Jan 11 '13 at 11:42