Thursday, October 28, 2010

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 will you do it...

I always wondered 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
catch(InterruptedException e)
    // If we reach here, that means sleep was interrrupted before 1000 ms.

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 :

No comments:

Post a Comment