2 * Copyright 2014 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <folly/io/async/AsyncTimeout.h>
20 #include <folly/io/async/DelayedDestruction.h>
22 #include <boost/intrusive/list.hpp>
23 #include <glog/logging.h>
33 * Hashed Hierarchical Wheel Timer
36 * TAsyncTimeout - a single timeout.
37 * HHWheelTimer - a set of efficient timeouts with different interval,
38 * but timeouts are not exact.
40 * All of the above are O(1) in insertion, tick update and cancel
42 * This implementation ticks once every 10ms.
43 * We model timers as the number of ticks until the next
44 * due event. We allow 32-bits of space to track this
45 * due interval, and break that into 4 regions of 8 bits.
46 * Each region indexes into a bucket of 256 lists.
48 * Bucket 0 represents those events that are due the soonest.
49 * Each tick causes us to look at the next list in a bucket.
50 * The 0th list in a bucket is special; it means that it is time to
51 * flush the timers from the next higher bucket and schedule them
52 * into a different bucket.
54 * This technique results in a very cheap mechanism for
55 * maintaining time and timers, provided that we can maintain
56 * a consistent rate of ticks.
58 class HHWheelTimer : private folly::AsyncTimeout,
59 public folly::DelayedDestruction {
61 typedef std::unique_ptr<HHWheelTimer, Destructor> UniquePtr;
64 * A callback to be notified when a timeout has expired.
75 * timeoutExpired() is invoked when the timeout has expired.
77 virtual void timeoutExpired() noexcept = 0;
80 * Cancel the timeout, if it is running.
82 * If the timeout is not scheduled, cancelTimeout() does nothing.
84 void cancelTimeout() {
85 if (wheel_ == nullptr) {
86 // We're not scheduled, so there's nothing to do.
93 * Return true if this timeout is currently scheduled, and false otherwise.
95 bool isScheduled() const {
96 return wheel_ != nullptr;
101 * Don't override this unless you're doing a test. This is mainly here so
102 * that we can override it to simulate lag in steady_clock.
104 virtual std::chrono::milliseconds getCurTime() {
105 return std::chrono::duration_cast<std::chrono::milliseconds>(
106 std::chrono::steady_clock::now().time_since_epoch());
110 // Get the time remaining until this timeout expires
111 std::chrono::milliseconds getTimeRemaining(
112 std::chrono::milliseconds now) const {
113 if (now >= expiration_) {
114 return std::chrono::milliseconds(0);
116 return expiration_ - now;
119 void setScheduled(HHWheelTimer* wheel,
120 std::chrono::milliseconds);
121 void cancelTimeoutImpl();
123 HHWheelTimer* wheel_;
124 std::chrono::milliseconds expiration_;
126 typedef boost::intrusive::list_member_hook<
127 boost::intrusive::link_mode<boost::intrusive::auto_unlink> > ListHook;
131 typedef boost::intrusive::list<
133 boost::intrusive::member_hook<Callback, ListHook, &Callback::hook_>,
134 boost::intrusive::constant_time_size<false> > List;
136 std::shared_ptr<RequestContext> context_;
138 // Give HHWheelTimer direct access to our members so it can take care
139 // of scheduling/cancelling.
140 friend class HHWheelTimer;
144 * Create a new HHWheelTimer with the specified interval.
146 static int DEFAULT_TICK_INTERVAL;
147 explicit HHWheelTimer(folly::EventBase* eventBase,
148 std::chrono::milliseconds intervalMS =
149 std::chrono::milliseconds(DEFAULT_TICK_INTERVAL));
152 * Destroy the HHWheelTimer.
154 * A HHWheelTimer should only be destroyed when there are no more
155 * callbacks pending in the set.
157 virtual void destroy();
160 * Get the tick interval for this HHWheelTimer.
162 * Returns the tick interval in milliseconds.
164 std::chrono::milliseconds getTickInterval() const {
169 * Schedule the specified Callback to be invoked after the
170 * specified timeout interval.
172 * If the callback is already scheduled, this cancels the existing timeout
173 * before scheduling the new timeout.
175 void scheduleTimeout(Callback* callback,
176 std::chrono::milliseconds timeout);
177 void scheduleTimeoutImpl(Callback* callback,
178 std::chrono::milliseconds timeout);
181 void scheduleTimeoutFn(F fn, std::chrono::milliseconds timeout) {
182 struct Wrapper : Callback {
183 Wrapper(F f) : fn_(std::move(f)) {}
184 void timeoutExpired() noexcept override {
187 } catch (std::exception const& e) {
188 LOG(ERROR) << "HHWheelTimer timeout callback threw an exception: "
191 LOG(ERROR) << "HHWheelTimer timeout callback threw a non-exception.";
197 Wrapper* w = new Wrapper(std::move(fn));
198 scheduleTimeout(w, timeout);
202 * Return the number of currently pending timeouts
204 uint64_t count() const {
209 * This turns on more exact timing. By default the wheel timer
210 * increments its cached time only once everyN (default) ticks.
212 * With catchupEveryN at 1, timeouts will only be delayed until the
213 * next tick, at which point all overdue timeouts are called. The
214 * wheel timer is approximately 2x slower with this set to 1.
216 * Load testing in opt mode showed skew was about 1% with no catchup.
218 void setCatchupEveryN(uint32_t everyN) {
219 catchupEveryN_ = everyN;
222 bool isDetachable() const {
223 return !folly::AsyncTimeout::isScheduled();
226 using folly::AsyncTimeout::attachEventBase;
227 using folly::AsyncTimeout::detachEventBase;
228 using folly::AsyncTimeout::getTimeoutManager;
232 * Protected destructor.
234 * Use destroy() instead. See the comments in DelayedDestruction for more
237 virtual ~HHWheelTimer();
240 // Forbidden copy constructor and assignment operator
241 HHWheelTimer(HHWheelTimer const &) = delete;
242 HHWheelTimer& operator=(HHWheelTimer const &) = delete;
244 // Methods inherited from TAsyncTimeout
245 virtual void timeoutExpired() noexcept;
247 std::chrono::milliseconds interval_;
249 static constexpr int WHEEL_BUCKETS = 4;
250 static constexpr int WHEEL_BITS = 8;
251 static constexpr unsigned int WHEEL_SIZE = (1 << WHEEL_BITS);
252 static constexpr unsigned int WHEEL_MASK = (WHEEL_SIZE - 1);
253 static constexpr uint32_t LARGEST_SLOT = 0xffffffffUL;
255 typedef Callback::List CallbackList;
256 CallbackList buckets_[WHEEL_BUCKETS][WHEEL_SIZE];
258 int64_t timeToWheelTicks(std::chrono::milliseconds t) {
259 return t.count() / interval_.count();
262 bool cascadeTimers(int bucket, int tick);
265 std::chrono::milliseconds now_;
267 static constexpr uint32_t DEFAULT_CATCHUP_EVERY_N = 10;
269 uint32_t catchupEveryN_;
270 uint32_t expirationsSinceCatchup_;
271 bool processingCallbacksGuard_;