-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
ManuallyScheduleHeartbeat.java
86 lines (75 loc) · 2.56 KB
/
ManuallyScheduleHeartbeat.java
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
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.heartbeat;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A rule which will temporarily change a heartbeat to being manually scheduled. See
* {@link HeartbeatScheduler}.
*/
public final class ManuallyScheduleHeartbeat implements TestRule {
private final List<String> mThreads;
/**
* @param threads names of the threads to manually schedule; names are defined in
* {@link HeartbeatContext}
*/
public ManuallyScheduleHeartbeat(List<String> threads) {
mThreads = threads;
}
/**
* @param threads names of the threads to manually schedule; names are defined in
* {@link HeartbeatContext}
*/
public ManuallyScheduleHeartbeat(String... threads) {
this(Arrays.asList(threads));
}
/**
* Stores executor threads and corresponding timer class.
*/
public static class Resource implements AutoCloseable {
private final List<String> mThreads;
private final Map<String, Class<? extends HeartbeatTimer>> mPrevious;
public Resource(List<String> threads) {
mThreads = threads;
mPrevious = new HashMap<>();
for (String threadName : mThreads) {
try {
mPrevious.put(threadName, HeartbeatContext.getTimerClass(threadName));
HeartbeatContext.setTimerClass(threadName, HeartbeatContext.SCHEDULED_TIMER_CLASS);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@Override
public void close() throws Exception {
for (String threadName : mThreads) {
HeartbeatContext.setTimerClass(threadName, mPrevious.get(threadName));
}
}
}
@Override
public Statement apply(final Statement statement, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try (Resource resource = new Resource(mThreads)) {
statement.evaluate();
}
}
};
}
}