How can I wrap a method so that I can kill its execution if it exceeds a specified timeout?

后端 未结 7 1776
陌清茗
陌清茗 2020-11-30 08:55

I have a method that I would like to call. However, I\'m looking for a clean, simple way to kill it or force it to return if it is taking too long to execute.

I\'m

7条回答
  •  伪装坚强ぢ
    2020-11-30 09:35

    Java's interruption mechanism is intended for this kind of scenario. If the method that you wish to abort is executing a loop, just have it check the thread's interrupted status on every iteration. If it's interrupted, throw an InterruptedException.

    Then, when you want to abort, you just have to invoke interrupt on the appropriate thread.

    Alternatively, you can use the approach Sun suggest as an alternative to the deprecated stop method. This doesn't involve throwing any exceptions, the method would just return normally.

提交回复
热议问题