Saturday, May 26, 2012

How to put a time restriction on a method in java?

I have a specific requirement where in I am calling a method and I want to get the response within a specific duration.
For example, I am trying to fetch the contents of a web-page.

If within 3 seconds, I get the response, its good, otherwise, I want to give a message to the user that internet is too slow.

Now, how do I do this?

You could make use of the ExecutorService and its timeout facilities. The idea is to execute the method you want to call in a different thread, and let the ExecutorService cancel it after a specific time. Here is a simple example, using two fixed threads. You'd have to adapt this to your needs.

Make a class MyTask implements Callable<Void>


Use this as is done here

No comments:

Post a Comment