1

I want to stop the method after x seconds. How do I do it ?

EDIT
I will elaborate: My method() is either native or communicates to other server.
I am not in a loop (Hence I cant change a flag) I will want to use the return value of the method if it exists.

Bick
  • 17,833
  • 52
  • 146
  • 251
  • 5
    See http://stackoverflow.com/questions/2733356/killing-thread-after-some-specified-time-limit-in-java – armandino Apr 27 '11 at 06:35

4 Answers4

2

That heavily depends on what your method is doing. The simplest approach would be to periodically check how long the method has been executing and return when the limit is exceeded.

long t0 = System.currentTimeMillis();
// do something
long t1 = System.currentTimeMillis();
if (t1-t0 > x*1000) {
    return;
}

If you want to run the method in a separate thread, then you could do something like this:

public <T> T myMethod() {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        try {
            T value = executor.invokeAny(Collections.singleton(new Callable<T>() {
                @Override
                public T call() throws Exception {
                    //your actual method code here
                    return null;
                }
            }), 3, TimeUnit.SECONDS);
            System.out.println("All went fine");
            return value;
        } catch (TimeoutException e) {
            System.out.println("Exceeded time limit, interrupted");
        } catch (Exception e) {
            System.out.println("Some error happened, handle it properly");
        }
        return null; /*some default value*/
    } finally {
        executor.shutdownNow();
    }
}

Please note that if you're doing some un-interruptible IO in the thread, this method will not work..

denis.solonenko
  • 11,645
  • 2
  • 28
  • 23
  • can I use mt method return value? like Callable? – Bick Apr 27 '11 at 07:07
  • @user450602 yes the invokeAny method returns the return value (see http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorService.html). – dacwe Apr 27 '11 at 07:18
1

The most reliable method - to my opinion - is a multithreading solution. I'd put the long running algorithm in a Runnable and use ExecutorService to execute the thread with a given timeout.

Answers to this question provide more details on the solution.

Of course, now the method will be exectued in parallel to the main thread, but you can force single thread behaviour with Thread#join - simply wait with your main thread until the time limited worker thread has finished or exceeded it's timeout limit.

Community
  • 1
  • 1
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268
0

It depends on what you're doing and how accurate you need to be. If you are in a loop, you can keep track of how much time has passed using System.currentTimeMillis(). Just get the time when you start and periodically check and see how long has passed.

You could spawn a new thread to start your processing, sleep for x seconds and then do something to stop the processing thread.

MattRS
  • 428
  • 5
  • 8
0

you can not do so in single execution you must use thread for that

i agree with armandino

see this

Community
  • 1
  • 1
Nirmal- thInk beYond
  • 11,847
  • 8
  • 35
  • 46