Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set running time limit on a method in java

Tags:

java

string

I have a method that returns a String.

Is it possible that after a certain time, if threshold is excedeed for that method, to return some specific string?

like image 962
London Avatar asked Mar 09 '11 08:03

London


1 Answers

I did something similar in the past when spawning an external process with Runtime.getRuntime().exec(command). I think you could do something like this within your method:

Timer timer = new Timer(true);
InterruptTimerTask interruptTimerTask = new InterruptTimerTask(Thread.currentThread());
timer.schedule(interruptTimerTask, waitTimeout);
try {
    // put here the portion of code that may take more than "waitTimeout"
}
catch (InterruptedException e) {
    log.error("timeout exeeded");
}
finally {
    timer.cancel();
}

and here is InterruptTimerTask

/*
 * A TimerTask that interrupts the specified thread when run.
 */
protected class InterruptTimerTask extends TimerTask {

    private Thread theTread;
    
    public InterruptTimerTask(Thread theTread) {
        this.theTread = theTread;
    }

    @Override
    public void run() {
        theTread.interrupt();
    }
}
like image 118
MarcoS Avatar answered Oct 02 '22 22:10

MarcoS