1/*
2 * Copyright (c) 2018, 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
25#include "precompiled.hpp"
26#include "runtime/os.hpp"
27#include "utilities/ostream.hpp"
28#include "utilities/spinYield.hpp"
29
30SpinYield::SpinYield(uint spin_limit, uint yield_limit, uint sleep_ns) :
31 _sleep_time(),
32 _spins(0),
33 _yields(0),
34 _spin_limit(os::is_MP() ? spin_limit : 0),
35 _yield_limit(yield_limit),
36 _sleep_ns(sleep_ns)
37{}
38
39void SpinYield::yield_or_sleep() {
40 if (_yields < _yield_limit) {
41 ++_yields;
42 os::naked_yield();
43 } else {
44 Ticks sleep_start = Ticks::now();
45 os::naked_short_nanosleep(_sleep_ns);
46 _sleep_time += Ticks::now() - sleep_start;
47 }
48}
49
50static const char* print_separator(outputStream* s, const char* separator) {
51 s->print("%s", separator);
52 return ", ";
53}
54
55void SpinYield::report(outputStream* s) const {
56 const char* initial_separator = "";
57 const char* separator = initial_separator;
58 if (_spins > 0) { // Report spins, if any.
59 separator = print_separator(s, separator);
60 s->print("spins = %u", _spins);
61 }
62 if (_yields > 0) { // Report yields, if any.
63 separator = print_separator(s, separator);
64 s->print("yields = %u", _yields);
65 }
66 if (_sleep_time.value() != 0) { // Report sleep duration, if slept.
67 separator = print_separator(s, separator);
68 s->print("sleep = " UINT64_FORMAT " usecs",
69 _sleep_time.milliseconds());
70 }
71 if (separator == initial_separator) {
72 s->print("no waiting");
73 }
74}
75