0

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;
        }
    }
nanosoft
  • 2,913
  • 4
  • 41
  • 61
  • As mentioned by @NirLevy - possible duplicate, and already answered here: http://stackoverflow.com/a/241534/5127499 – Carsten Aug 24 '15 at 22:18

3 Answers3

2

You need another thread (possibly shielded by an ExecutorService) and a standard Future<T>. First wrap your long running task in a Callable<T>:

public class LongRunningTask implements Callable<String> {
  public String call() throws Exception { /* ... */ }
}

And then call it like this:

ExecutorService service;
LongRunningTask longRunningTask;

public String test() throws Exception {
  Future<?> future = service.submit(longRunningTask);
  return future.get(10, TimeUnit.SECONDS);
}
Raffaele
  • 20,627
  • 6
  • 47
  • 86
1

using Callable is one easy way to go. there's a very nice example here

Community
  • 1
  • 1
Nir Levy
  • 12,750
  • 3
  • 21
  • 38
0

Set a 10 second timer (I would use the preinstalled one from java.util) then say if the timer reaches 10 seconds, the method should return "default value"

Bill Bllson
  • 179
  • 1
  • 1
  • 14