Tuesday, August 28, 2012

Java Network Timeout handling

So this blog post (via stackoverflow as usual) points out that you need to manually handle timing out reads when using URLConnection and hence also HttpURLConnection.

The post also helpfully provides example code for such a manual timer:

try {
    URLConnection con = urlObj.openConnection();
    con.setConnectTimeout(5000);
    con.setReadTimeout(5000);
    new Thread(new InterruptThread(Thread.currentThread(), con)).start();
    retVal = new Source(con);
} catch (IOException e) {
    System.err.println("aborted parsing due to I/O: " + e.getMessage());
    throw new IndexingException("aborted parsing due to timeout - " + aUrl);
}

public class InterruptThread implements Runnable {
    Thread parent;
    URLConnection con;
    public InterruptThread(Thread parent, URLConnection con) {
        this.parent = parent;
        this.con = con;
    }

    public void run() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {

        }
        System.out.println("Timer thread forcing parent to quit connection");
        ((HttpURLConnection)con).disconnect();
        System.out.println("Timer thread closed connection held by parent, exiting");
    }
}

No comments:

Post a Comment