2

I am using Jtidy parser in java.Here is my code...

  URL url = new URL("www.yahoo.com");
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  InputStream in = conn.getInputStream();
  Tidy tidy = new Tidy();
  Document doc = tidy.parseDOM(in, null);

when I come to this statement Document doc = tidy.parseDOM(in, null);,it is taking too much time to parse the page, so I want to set the time limit to document object. Please help me, how to set time.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
DJ31
  • 1,219
  • 3
  • 14
  • 19

1 Answers1

3

You could use the java.util.Executors framework and submit a time-limited task to it.

Here's some code that demonstrates this:

// Note that these variables must be declared final to be accessible to task
final InputStream in = conn.getInputStream();
final Tidy tidy = new Tidy();

ExecutorService service = Executors.newSingleThreadExecutor();
// Create an anonymous class that will be submitted to the service and returns your result
Callable<Document> task = new Callable<Document>() {
    public Document call() throws Exception {
        return tidy.parseDOM(in, null);
    }
};
Future<Document> future = service.submit(task);
// Future.get() offers a timed version that may throw a TimeoutException
Document doc = future.get(10, TimeUnit.SECONDS);
Bohemian
  • 412,405
  • 93
  • 575
  • 722