Link to home
Start Free TrialLog in
Avatar of ff10
ff10

asked on

Time limited Java task

I would like to limit the amount of time that a particular calculation can take in Java.  If the calculation exceeds this amount of time, the task should throw an exception.  I envision the call would be something like this:
Callable c = <defining the calculation>
Result r = null;
try {
r = new TimeBoundedTask(c, 10000 /* 10 seconds */);
} catch (OutOfTimeException e) {

}

Before rolling my own, I hope someone can refer me to a library that does this and has been tested.
Avatar of cmalakar
cmalakar
Flag of India image

I dont think.. this can be done direct api.

We can use stop() method of a thread to acheive this.. but that is deprecated.

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#stop%28%29
Avatar of sciuriware
sciuriware

You must set a timertask inside the same thread.
The 'actionPerformed()' of this timer can stop the thread (its own thread!)
or it can set a flag that is 'heeded' by the calculating process to make it
go away smoothly.

;JOOP!
ASKER CERTIFIED SOLUTION
Avatar of sciuriware
sciuriware

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Remark: the swing-timer is a repeating one, but that won't hurt you here.

;JOOP!
Avatar of ff10

ASKER

I was hoping to find something in JDK 6 that didn't get us so low level in the code (killing threads).  

The solution is definitely creative!