Reputation: 1191
How can I make such thing possible in java ? Or to be more presice I would like to make timeout for my function.
Pseudo code:
public String aLotOfWork()
{
return hardWork();
if(hardWork() is still executing after 30 seconds)
return "TimeOut";
}
I can use TimerTask for this but I cannot return any value from timer task run() to my upper function
TimerTask task = new TimerTask() {
public void run()
{
return ""; // timerTask run must be void.
}
};
Timer timer = new Timer();
timer.schedule(task, 50000, 1);
Upvotes: 2
Views: 153
Reputation: 15119
Checkout the FutureTask class. It provides a method called get(timeout, timeUnit)
. Off load the hardwork
task to the FutureTask
Class
public String aLotOfWork() {
FutureTask task = new FutureTask<String>(new Callable<String>() {
public String call() {
return hardwork();
}
});
try {
return task.get(30, TimeUnit.SECONDS);
} catch(TimeoutException e) {
return "Timeout";
}
catch(Exception e) {
return "Timeout"; // or whatever you like
}
}
Upvotes: 4
Reputation: 214
void method() {
long endTimeMillis = System.currentTimeMillis() + 10000;
while (true) {
// method logic
if (System.currentTimeMillis() > endTimeMillis) {
// do some clean-up
return;
}
}
}
Upvotes: 0