1/*
2 * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24#include "precompiled.hpp"
25#include "gc/z/zMetronome.hpp"
26#include "runtime/mutexLocker.hpp"
27#include "runtime/timer.hpp"
28#include "utilities/ticks.hpp"
29
30ZMetronome::ZMetronome(uint64_t hz) :
31 _monitor(Monitor::leaf, "ZMetronome", false, Monitor::_safepoint_check_never),
32 _interval_ms(MILLIUNITS / hz),
33 _start_ms(0),
34 _nticks(0),
35 _stopped(false) {}
36
37bool ZMetronome::wait_for_tick() {
38 if (_nticks++ == 0) {
39 // First tick, set start time
40 const Ticks now = Ticks::now();
41 _start_ms = TimeHelper::counter_to_millis(now.value());
42 }
43
44 MonitorLocker ml(&_monitor, Monitor::_no_safepoint_check_flag);
45
46 while (!_stopped) {
47 // We might wake up spuriously from wait, so always recalculate
48 // the timeout after a wakeup to see if we need to wait again.
49 const Ticks now = Ticks::now();
50 const uint64_t now_ms = TimeHelper::counter_to_millis(now.value());
51 const uint64_t next_ms = _start_ms + (_interval_ms * _nticks);
52 const int64_t timeout_ms = next_ms - now_ms;
53
54 if (timeout_ms > 0) {
55 // Wait
56 ml.wait(timeout_ms);
57 } else {
58 // Tick
59 if (timeout_ms < 0) {
60 const uint64_t overslept = -timeout_ms;
61 if (overslept > _interval_ms) {
62 // Missed one or more ticks. Bump _nticks accordingly to
63 // avoid firing a string of immediate ticks to make up
64 // for the ones we missed.
65 _nticks += overslept / _interval_ms;
66 }
67 }
68
69 return true;
70 }
71 }
72
73 // Stopped
74 return false;
75}
76
77void ZMetronome::stop() {
78 MonitorLocker ml(&_monitor, Monitor::_no_safepoint_check_flag);
79 _stopped = true;
80 ml.notify();
81}
82