Content Table

Watchdog

可以使用 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import org.apache.commons.exec.Watchdog;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class Test {
private static final SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");

public static void main(String[] args) {
Thread thread = new Thread(() -> {
// 创建 watchdog
Thread t = Thread.currentThread();
Watchdog watchdog = new Watchdog(TimeUnit.SECONDS.toMillis(1));

// 超时且未关闭 watchdog 时执行的操作
watchdog.addTimeoutObserver(w -> {
System.out.println("Watchdog trigger");
t.interrupt();
});

// 启动 watchdog
watchdog.start();

// 执行耗时任务,超时的时候当前线程的 isInterrupted() 为 true,结束循环
System.out.println("开始时间: " + formatter.format(new Date()));
int count = 0;
StringBuilder sb = new StringBuilder();
while (!t.isInterrupted() && count++ < 10000) {
sb.append(count);
}
System.out.printf("结束时间: %s,循环次数: %d", formatter.format(new Date()), count);

// 关闭 watchdog
watchdog.stop();
});

thread.start();
}
}

输出:

1
2
3
开始时间: 01:51:40
Watchdog trigger
结束时间: 01:51:41,循环次数: 48060741

Watchdog.java

Watchdog 的实现很简单,创建一个 Daemon 线程,在 run 方法中等待超时,然后执行注册的 TimeoutObserver。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* 
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

package org.apache.commons.exec;

import java.util.Enumeration;
import java.util.Vector;

/**
* Generalization of {@code ExecuteWatchdog}
*
* @see org.apache.commons.exec.ExecuteWatchdog
*
* @version $Id: Watchdog.java 1636056 2014-11-01 21:12:52Z ggregory $
*/
public class Watchdog implements Runnable {

private final Vector<TimeoutObserver> observers = new Vector<TimeoutObserver>(1);

private final long timeout;

private boolean stopped = false;

public Watchdog(final long timeout) {
if (timeout < 1) {
throw new IllegalArgumentException("timeout must not be less than 1.");
}
this.timeout = timeout;
}

public void addTimeoutObserver(final TimeoutObserver to) {
observers.addElement(to);
}

public void removeTimeoutObserver(final TimeoutObserver to) {
observers.removeElement(to);
}

protected final void fireTimeoutOccured() {
final Enumeration<TimeoutObserver> e = observers.elements();
while (e.hasMoreElements()) {
e.nextElement().timeoutOccured(this);
}
}

public synchronized void start() {
stopped = false;
final Thread t = new Thread(this, "WATCHDOG");
t.setDaemon(true);
t.start();
}

public synchronized void stop() {
stopped = true;
notifyAll();
}

public void run() {
final long startTime = System.currentTimeMillis();
boolean isWaiting;
synchronized (this) {
long timeLeft = timeout - (System.currentTimeMillis() - startTime);
isWaiting = timeLeft > 0;
while (!stopped && isWaiting) {
try {
wait(timeLeft);
} catch (final InterruptedException e) {
}
timeLeft = timeout - (System.currentTimeMillis() - startTime);
isWaiting = timeLeft > 0;
}
}

// notify the listeners outside of the synchronized block (see EXEC-60)
if (!isWaiting) {
fireTimeoutOccured();
}
}
}