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 #ifndef SHARE_GC_Z_ZLOCK_INLINE_HPP
  25 #define SHARE_GC_Z_ZLOCK_INLINE_HPP
  26 
  27 #include "gc/z/zLock.hpp"
  28 #include "runtime/atomic.hpp"
  29 #include "runtime/os.inline.hpp"
  30 #include "runtime/thread.hpp"
  31 #include "utilities/debug.hpp"
  32 
  33 inline void ZLock::lock() {
  34   _lock.lock();
  35 }
  36 
  37 inline bool ZLock::try_lock() {
  38   return _lock.try_lock();
  39 }
  40 
  41 inline void ZLock::unlock() {
  42   _lock.unlock();
  43 }
  44 
  45 inline ZReentrantLock::ZReentrantLock() :
  46     _lock(),
  47     _owner(NULL),
  48     _count(0) {}
  49 
  50 inline void ZReentrantLock::lock() {
  51   Thread* const thread = Thread::current();
  52   Thread* const owner = Atomic::load(&_owner);
  53 
  54   if (owner != thread) {
  55     _lock.lock();
  56     Atomic::store(&_owner, thread);
  57   }
  58 
  59   _count++;
  60 }
  61 
  62 inline void ZReentrantLock::unlock() {
  63   assert(is_owned(), "Invalid owner");
  64   assert(_count > 0, "Invalid count");
  65 
  66   _count--;
  67 
  68   if (_count == 0) {
  69     Atomic::store(&_owner, (Thread*)NULL);
  70     _lock.unlock();
  71   }
  72 }
  73 
  74 inline bool ZReentrantLock::is_owned() const {
  75   Thread* const thread = Thread::current();
  76   Thread* const owner = Atomic::load(&_owner);
  77   return owner == thread;
  78 }
  79 
  80 template <typename T>
  81 inline ZLocker<T>::ZLocker(T* lock) :
  82     _lock(lock) {
  83   if (_lock != NULL) {
  84     _lock->lock();
  85   }
  86 }
  87 
  88 template <typename T>
  89 inline ZLocker<T>::~ZLocker() {
  90   if (_lock != NULL) {
  91     _lock->unlock();
  92   }
  93 }
  94 
  95 #endif // SHARE_GC_Z_ZLOCK_INLINE_HPP