How to set syntax duration limit for document object in java

I am using the Jtidy parser in java.Here 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 takes too much time to analyze the page, so I want to set a time limit for the document object. Please help me how to set the time.

+3
source share
1 answer

You can use the framework java.util.Executorsand send it a time-limited task.

Here is 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);
+3
source

All Articles