简体   繁体   中英

what is the best way to create a timeout to a method in java?

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.

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..

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.

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.

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

i agree with armandino

see this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM