I have one method m1() which calls another method m2(). As m2() is a long running method, I want to wait for it to return say for 10 secs and if not then I use a default value. Is there a way in Java where I can say run this method for at most this much time or return so that I don't have to wait long. Well I can do Thread.currentThread().sleep(x) but then even if my method returns earlier I will have to wait till x time.
So based on the answers, I wrote below Class:
I am using sleep in Callable so that it exceeds the call to get method, But it still return 1. What is wrong?
public class RunMethodAtMostForGivenTime
{
public static void main(String[] args)
{
RunMethodAtMostForGivenTime obj = new RunMethodAtMostForGivenTime();
System.out.println(obj.sum());
}
private int sum()
{
int sum = 1;
ExecutorService service = Executors.newFixedThreadPool(1);
int returnedInt = 0;
Future<Integer> calculatedIntFuture = service
.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception
{
Thread.currentThread().sleep(110);
return new Integer(1);
}
});
try
{
//here wait is for 10 milliseconds and callable thread sleeps for 110 milliseconds so expected returned value is 0 not 1.
returnedInt = calculatedIntFuture.get(10, TimeUnit.MILLISECONDS);
sum += returnedInt;
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
catch (TimeoutException e)
{
e.printStackTrace();
}
return sum;
}
}