可以使用 watchdog 控制某些耗时操作的超时时间,当超时的时候执行指定的操作,例如中断线程、重置 Redis key 的超时时间等。Apache 的 commons-exec 包中提供了 watchdog 的实现供我们使用 (源码为文章后面的 Watchdog.java)。
According to wikipedia - watchdog is an electronic timer that is used to detect and recover from computer malfunctions.
案例演示
下面的例子执行拼接字符串的耗时操作,定义了一个 watchdog,超时时间为 1S,超时后 watchdog 中断线程结束字符串拼接操作。
1 | import org.apache.commons.exec.Watchdog; |
输出:
1 | 开始时间: 01:51:40 |