1/*
2 * Copyright (c) 2014, 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
25#ifndef SHARE_JFR_UTILITIES_JFRTRYLOCK_HPP
26#define SHARE_JFR_UTILITIES_JFRTRYLOCK_HPP
27
28#include "runtime/atomic.hpp"
29#include "runtime/orderAccess.hpp"
30#include "runtime/mutexLocker.hpp"
31#include "utilities/debug.hpp"
32
33class JfrTryLock {
34 private:
35 volatile int* const _lock;
36 bool _has_lock;
37
38 public:
39 JfrTryLock(volatile int* lock) : _lock(lock), _has_lock(Atomic::cmpxchg(1, lock, 0) == 0) {}
40
41 ~JfrTryLock() {
42 if (_has_lock) {
43 OrderAccess::fence();
44 *_lock = 0;
45 }
46 }
47
48 bool has_lock() const {
49 return _has_lock;
50 }
51};
52
53class JfrMonitorTryLock : public StackObj {
54 private:
55 Monitor* _lock;
56 bool _acquired;
57
58 public:
59 JfrMonitorTryLock(Monitor* lock) : _lock(lock), _acquired(lock->try_lock()) {}
60
61 ~JfrMonitorTryLock() {
62 if (_acquired) {
63 assert(_lock->owned_by_self(), "invariant");
64 _lock->unlock();
65 }
66 }
67
68 bool acquired() const {
69 return _acquired;
70 }
71
72};
73
74#endif // SHARE_JFR_UTILITIES_JFRTRYLOCK_HPP
75