Is it possible to stop a function's execution within a specified time in Java?

守給你的承諾、 提交于 2019-12-12 11:02:21

问题


I want to know how to stop a specified function's execution within a specified time in java.

For example: I may call a function called print_data(). If it takes more time to execute, I will have to stop that function's execution.

Is it possible to stop the execution like this?

Thanks in advance


回答1:


You could add some checks to your function: save the timestamp when function started working and then periodically checking that inside the function, throwing an exception if function takes too long.

This is the cleanest way to accomplish such task in Java.




回答2:


There is no safe way to stop a thread executing, unless it is being cooperative; e.g. it regularly checks the 'interrupted' flag.

@BobbyShaftoe suggests this in a comment:

You could execute this function in a separate thread and then abort the thread after some period of time.

This is misleading and dangerous advice. The only way to "abort" a thread is to use the deprecated Thread.stop() method. If you look at the javadoc for that method you will see that it is a fundamentally dangerous method that is liable to have undesirable and unpredictable side-effects.

It should also be noted that @tonio's solution doesn't stop the function's execution. It simply stops waiting for the function's execution to finish. The function could continue executing indefinitely, chewing up resources to no good effect.




回答3:


You can use the TimeUnit enum from java.util.concurrent, in particular the timedJoin method.

You specify a time to wait, and a thread. timedJoin will let your thread execute until termination, or stop if the processing takes more time than the timeout allowed. You can use an anonymous class to wrap your method in a Thread object easily.

This can be as easy as:

SECONDS.timedJoin(
    new Thread() {
      public void run() {
        print_data();
      }
    },
    10);    

for a 10 seconds timeout.



来源:https://stackoverflow.com/questions/3183722/is-it-possible-to-stop-a-functions-execution-within-a-specified-time-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!