Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Timeouts for BufferedReader while parsing HTML pages

843790Aug 1 2006 — edited Jan 16 2007
Hello,

I am looking for a good sollution for implementation of timeouts in BufferedReader. I use HTML parser with callbacks for parsing HTML and sometimes it hangs forever due to server timeouts at the server side. So i need a timeout built in BufferedReader to interrupt hanged parsing. I found this sollution, but it is not good for networking:
import java.io.BufferedReader;
import java.io.IOException;

public class TimedBufferedReader extends BufferedReader {

                private int 	timeout 		= 0;
                BufferedReader in;

                /**
                  * TimedBufferedReader constructor.
                  * @param in java.io.Reader
                  */
                TimedBufferedReader(java.io.Reader in) {
                        this(in,1024);
                }

                /**
                  * TimedBufferedReader constructor.
                  * @param in java.io.Reader
                  * @param sz int Size of the input buffer.
                  */
                TimedBufferedReader(java.io.Reader in, int sz) {
                        super(in, sz);
                        this.in=(BufferedReader)in;
                }

                /**
                  * Sets number of seconds to block for input.
                  * @param seconds int
                  */
                public void setTimeout(int millyseconds) {
                        timeout=millyseconds*10;
                }

                public int read(char buf[]) throws IOException
                {
                  int msec = 0;
                  while (!this.in.ready()) {
                    try { Thread.currentThread().sleep(100); }
                    catch (InterruptedException e) { break; }
                     msec+=100;
                    if (this.in.ready()) return this.in.read(buf);
                    if (msec >= timeout)
                    {
                      throw new IOException("Timeout for reading");
                    }
                  }
                  return this.in.read(buf);
                }
              }
I modified this several times and none of my modifications worked for HTML parsing with callbacks. It allways gives timeout. Even if it founds good URL.

Please kindly help.

Thanks in advance,
F.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 13 2007
Added on Aug 1 2006
15 comments
1,127 views