How to put limitation of time on a method call

Lets say, you are reading a website, and you want that, if you get a response within 3 seconds then its ok..
otherwise, you want to give a message to user that internet is tooo slow…how will you do it…

I always wondered it…today found a solution…Not tooo complex, its just that, i was not able to develop this logic using my own knowledge of java. 🙂

This is just an example:
Declare a private Thread mainThread;

final int factorialOf = 1 + (int) (30000 * Math.random());
System.out.println("computing " + factorialOf + '!');

Thread testThread = new Thread() {

public void run() {
System.out.println(factorialOf + "! = " + Utils.computeFactorial(factorialOf));
//Now run method has completed its execution
// so it should interrupt the main Thread
mainThread.interrupt();
}
};
mainThread=Thread.currentThread();
testThread.start();
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
// If we reach here, that means sleep was interrrupted before 1000 ms.
}
testThread.interrupt();

if (testThread.isInterrupted()) {
throw new TimeoutException("the test took too long to complete");
}

PS: Though this should work, but some time is being taken by the statements which create new thread.

Some other/better methods are also given here : http://javakafunda.blogspot.in/2012/05/how-to-put-time-restriction-on-method.html

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.