1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.hadoop.hbase.util;
21
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24 import org.apache.hadoop.hbase.Stoppable;
25
26
27
28
29
30
31
32 public class Sleeper {
33 private final Log LOG = LogFactory.getLog(this.getClass().getName());
34 private final int period;
35 private final Stoppable stopper;
36 private static final long MINIMAL_DELTA_FOR_LOGGING = 10000;
37
38 private final Object sleepLock = new Object();
39 private boolean triggerWake = false;
40
41
42
43
44
45
46 public Sleeper(final int sleep, final Stoppable stopper) {
47 this.period = sleep;
48 this.stopper = stopper;
49 }
50
51
52
53
54 public void sleep() {
55 sleep(System.currentTimeMillis());
56 }
57
58
59
60
61
62 public void skipSleepCycle() {
63 synchronized (sleepLock) {
64 triggerWake = true;
65 sleepLock.notify();
66 }
67 }
68
69
70
71
72
73
74 public void sleep(final long startTime) {
75 if (this.stopper.isStopped()) {
76 return;
77 }
78 long now = System.currentTimeMillis();
79 long waitTime = this.period - (now - startTime);
80 if (waitTime > this.period) {
81 LOG.warn("Calculated wait time > " + this.period +
82 "; setting to this.period: " + System.currentTimeMillis() + ", " +
83 startTime);
84 waitTime = this.period;
85 }
86 while (waitTime > 0) {
87 long woke = -1;
88 try {
89 synchronized (sleepLock) {
90 if (triggerWake) break;
91 sleepLock.wait(waitTime);
92 }
93 woke = System.currentTimeMillis();
94 long slept = woke - now;
95 if (slept - this.period > MINIMAL_DELTA_FOR_LOGGING) {
96 LOG.warn("We slept " + slept + "ms instead of " + this.period +
97 "ms, this is likely due to a long " +
98 "garbage collecting pause and it's usually bad, " +
99 "see http://wiki.apache.org/hadoop/Hbase/Troubleshooting#A9");
100 }
101 } catch(InterruptedException iex) {
102
103
104 if (this.stopper.isStopped()) {
105 return;
106 }
107 }
108
109 woke = (woke == -1)? System.currentTimeMillis(): woke;
110 waitTime = this.period - (woke - startTime);
111 }
112 triggerWake = false;
113 }
114 }