Java: set timeout on a certain block of code?

前端 未结 11 1035
终归单人心
终归单人心 2020-11-27 03:45

Is it possible to force Java to throw an Exception after some block of code runs longer than acceptable?

11条回答
  •  被撕碎了的回忆
    2020-11-27 03:57

    Yes, but its generally a very bad idea to force another thread to interrupt on a random line of code. You would only do this if you intend to shutdown the process.

    What you can do is to use Thread.interrupt() for a task after a certain amount of time. However, unless the code checks for this it won't work. An ExecutorService can make this easier with Future.cancel(true)

    Its much better for the code to time itself and stop when it needs to.

提交回复
热议问题