1 /* 2 * Copyright (c) 2015, 2017, 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 30 ZMetronome::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 37 uint64_t ZMetronome::nticks() const { 38 return _nticks; 39 } 40 41 bool ZMetronome::wait_for_tick() { 42 if (_nticks++ == 0) { 43 // First tick, set start time 44 const Ticks now = Ticks::now(); 45 _start_ms = TimeHelper::counter_to_millis(now.value()); 46 } 47 48 for (;;) { 49 // We might wake up spuriously from wait, so always recalculate 50 // the timeout after a wakeup to see if we need to wait again. 51 const Ticks now = Ticks::now(); 52 const uint64_t now_ms = TimeHelper::counter_to_millis(now.value()); 53 const uint64_t next_ms = _start_ms + (_interval_ms * _nticks); 54 const int64_t timeout_ms = next_ms - now_ms; 55 56 MonitorLockerEx ml(&_monitor, Monitor::_no_safepoint_check_flag); 57 if (!_stopped && timeout_ms > 0) { 58 // Wait 59 ml.wait(Monitor::_no_safepoint_check_flag, timeout_ms); 60 } else { 61 // Tick 62 return !_stopped; 63 } 64 } 65 } 66 67 void ZMetronome::stop() { 68 MonitorLockerEx ml(&_monitor, Monitor::_no_safepoint_check_flag); 69 _stopped = true; 70 ml.notify(); 71 }