简体   繁体   English

为 java 中的方法创建超时的最佳方法是什么?

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

I want to stop the method after x seconds.我想在 x 秒后停止该方法。 How do I do it?我该怎么做?

EDIT编辑
I will elaborate: My method() is either native or communicates to other server.我将详细说明:我的 method() 要么是本机的,要么与其他服务器通信。
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..请注意,如果您在线程中执行一些不可中断的 IO,则此方法将不起作用..

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.我将长时间运行的算法放在Runnable中,并使用ExecutorService以给定的超时时间执行线程。

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.当然,现在该方法将与主线程并行执行,但您可以使用Thread#join强制执行单线程行为- 只需等待您的主线程,直到时间有限的工作线程完成或超过其超时限制。

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().如果您处于循环中,您可以使用 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.您可以生成一个新线程来开始处理,休眠 x 秒,然后做一些事情来停止处理线程。

you can not do so in single execution you must use thread for that您不能在单次执行中这样做,您必须为此使用线程

i agree with armandino我同意阿曼迪诺

see this 看到这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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