1 /*
   2  * Copyright (c) 1998, 2024, 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 "classfile/vmSymbols.hpp"
  27 #include "gc/shared/oopStorage.hpp"
  28 #include "gc/shared/oopStorageSet.hpp"
  29 #include "jfr/jfrEvents.hpp"
  30 #include "jfr/support/jfrThreadId.hpp"
  31 #include "logging/log.hpp"
  32 #include "logging/logStream.hpp"
  33 #include "memory/allocation.inline.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "oops/markWord.hpp"
  36 #include "oops/oop.inline.hpp"
  37 #include "oops/oopHandle.inline.hpp"
  38 #include "oops/weakHandle.inline.hpp"
  39 #include "prims/jvmtiDeferredUpdates.hpp"
  40 #include "prims/jvmtiExport.hpp"
  41 #include "runtime/atomic.hpp"

  42 #include "runtime/globals.hpp"
  43 #include "runtime/handles.inline.hpp"
  44 #include "runtime/interfaceSupport.inline.hpp"
  45 #include "runtime/javaThread.inline.hpp"
  46 #include "runtime/lightweightSynchronizer.hpp"
  47 #include "runtime/mutexLocker.hpp"
  48 #include "runtime/objectMonitor.hpp"
  49 #include "runtime/objectMonitor.inline.hpp"
  50 #include "runtime/orderAccess.hpp"
  51 #include "runtime/osThread.hpp"
  52 #include "runtime/perfData.hpp"
  53 #include "runtime/safefetch.hpp"
  54 #include "runtime/safepointMechanism.inline.hpp"
  55 #include "runtime/sharedRuntime.hpp"

  56 #include "services/threadService.hpp"
  57 #include "utilities/debug.hpp"
  58 #include "utilities/dtrace.hpp"
  59 #include "utilities/globalDefinitions.hpp"
  60 #include "utilities/macros.hpp"
  61 #include "utilities/preserveException.hpp"
  62 #if INCLUDE_JFR
  63 #include "jfr/support/jfrFlush.hpp"
  64 #endif
  65 
  66 #ifdef DTRACE_ENABLED
  67 
  68 // Only bother with this argument setup if dtrace is available
  69 // TODO-FIXME: probes should not fire when caller is _blocked.  assert() accordingly.
  70 
  71 
  72 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread)                           \
  73   char* bytes = nullptr;                                                   \
  74   int len = 0;                                                             \
  75   jlong jtid = SharedRuntime::get_java_tid(thread);                        \
  76   Symbol* klassname = obj->klass()->name();                                \
  77   if (klassname != nullptr) {                                              \
  78     bytes = (char*)klassname->bytes();                                     \
  79     len = klassname->utf8_length();                                        \
  80   }
  81 
  82 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis)            \
  83   {                                                                        \
  84     if (DTraceMonitorProbes) {                                             \
  85       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
  86       HOTSPOT_MONITOR_WAIT(jtid,                                           \
  87                            (monitor), bytes, len, (millis));               \
  88     }                                                                      \
  89   }
  90 
  91 #define HOTSPOT_MONITOR_contended__enter HOTSPOT_MONITOR_CONTENDED_ENTER
  92 #define HOTSPOT_MONITOR_contended__entered HOTSPOT_MONITOR_CONTENDED_ENTERED
  93 #define HOTSPOT_MONITOR_contended__exit HOTSPOT_MONITOR_CONTENDED_EXIT
  94 #define HOTSPOT_MONITOR_notify HOTSPOT_MONITOR_NOTIFY
  95 #define HOTSPOT_MONITOR_notifyAll HOTSPOT_MONITOR_NOTIFYALL
  96 
  97 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread)                  \
  98   {                                                                        \
  99     if (DTraceMonitorProbes) {                                             \
 100       DTRACE_MONITOR_PROBE_COMMON(obj, thread);                            \
 101       HOTSPOT_MONITOR_##probe(jtid,                                        \
 102                               (uintptr_t)(monitor), bytes, len);           \
 103     }                                                                      \
 104   }
 105 
 106 #else //  ndef DTRACE_ENABLED
 107 
 108 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon)    {;}
 109 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon)          {;}
 110 
 111 #endif // ndef DTRACE_ENABLED
 112 
 113 DEBUG_ONLY(static volatile bool InitDone = false;)
 114 
 115 OopStorage* ObjectMonitor::_oop_storage = nullptr;
 116 












 117 // -----------------------------------------------------------------------------
 118 // Theory of operations -- Monitors lists, thread residency, etc:
 119 //
 120 // * A thread acquires ownership of a monitor by successfully
 121 //   CAS()ing the _owner field from null to non-null.
 122 //
 123 // * Invariant: A thread appears on at most one monitor list --
 124 //   cxq, EntryList or WaitSet -- at any one time.
 125 //
 126 // * Contending threads "push" themselves onto the cxq with CAS
 127 //   and then spin/park.
 128 //
 129 // * After a contending thread eventually acquires the lock it must
 130 //   dequeue itself from either the EntryList or the cxq.
 131 //
 132 // * The exiting thread identifies and unparks an "heir presumptive"
 133 //   tentative successor thread on the EntryList.  Critically, the
 134 //   exiting thread doesn't unlink the successor thread from the EntryList.
 135 //   After having been unparked, the wakee will recontend for ownership of
 136 //   the monitor.   The successor (wakee) will either acquire the lock or
 137 //   re-park itself.
 138 //
 139 //   Succession is provided for by a policy of competitive handoff.
 140 //   The exiting thread does _not_ grant or pass ownership to the
 141 //   successor thread.  (This is also referred to as "handoff" succession").
 142 //   Instead the exiting thread releases ownership and possibly wakes
 143 //   a successor, so the successor can (re)compete for ownership of the lock.
 144 //   If the EntryList is empty but the cxq is populated the exiting
 145 //   thread will drain the cxq into the EntryList.  It does so by
 146 //   by detaching the cxq (installing null with CAS) and folding
 147 //   the threads from the cxq into the EntryList.  The EntryList is
 148 //   doubly linked, while the cxq is singly linked because of the
 149 //   CAS-based "push" used to enqueue recently arrived threads (RATs).
 150 //
 151 // * Concurrency invariants:
 152 //
 153 //   -- only the monitor owner may access or mutate the EntryList.
 154 //      The mutex property of the monitor itself protects the EntryList
 155 //      from concurrent interference.
 156 //   -- Only the monitor owner may detach the cxq.
 157 //
 158 // * The monitor entry list operations avoid locks, but strictly speaking
 159 //   they're not lock-free.  Enter is lock-free, exit is not.
 160 //   For a description of 'Methods and apparatus providing non-blocking access
 161 //   to a resource,' see U.S. Pat. No. 7844973.
 162 //
 163 // * The cxq can have multiple concurrent "pushers" but only one concurrent
 164 //   detaching thread.  This mechanism is immune from the ABA corruption.
 165 //   More precisely, the CAS-based "push" onto cxq is ABA-oblivious.
 166 //
 167 // * Taken together, the cxq and the EntryList constitute or form a
 168 //   single logical queue of threads stalled trying to acquire the lock.
 169 //   We use two distinct lists to improve the odds of a constant-time
 170 //   dequeue operation after acquisition (in the ::enter() epilogue) and
 171 //   to reduce heat on the list ends.  (c.f. Michael Scott's "2Q" algorithm).
 172 //   A key desideratum is to minimize queue & monitor metadata manipulation
 173 //   that occurs while holding the monitor lock -- that is, we want to
 174 //   minimize monitor lock holds times.  Note that even a small amount of
 175 //   fixed spinning will greatly reduce the # of enqueue-dequeue operations
 176 //   on EntryList|cxq.  That is, spinning relieves contention on the "inner"
 177 //   locks and monitor metadata.
 178 //
 179 //   Cxq points to the set of Recently Arrived Threads attempting entry.
 180 //   Because we push threads onto _cxq with CAS, the RATs must take the form of
 181 //   a singly-linked LIFO.  We drain _cxq into EntryList  at unlock-time when
 182 //   the unlocking thread notices that EntryList is null but _cxq is != null.
 183 //
 184 //   The EntryList is ordered by the prevailing queue discipline and
 185 //   can be organized in any convenient fashion, such as a doubly-linked list or
 186 //   a circular doubly-linked list.  Critically, we want insert and delete operations
 187 //   to operate in constant-time.  If we need a priority queue then something akin
 188 //   to Solaris' sleepq would work nicely.  Viz.,
 189 //   http://agg.eng/ws/on10_nightly/source/usr/src/uts/common/os/sleepq.c.
 190 //   Queue discipline is enforced at ::exit() time, when the unlocking thread
 191 //   drains the cxq into the EntryList, and orders or reorders the threads on the
 192 //   EntryList accordingly.
 193 //
 194 //   Barring "lock barging", this mechanism provides fair cyclic ordering,
 195 //   somewhat similar to an elevator-scan.
 196 //
 197 // * The monitor synchronization subsystem avoids the use of native
 198 //   synchronization primitives except for the narrow platform-specific
 199 //   park-unpark abstraction.  See the comments in os_solaris.cpp regarding
 200 //   the semantics of park-unpark.  Put another way, this monitor implementation
 201 //   depends only on atomic operations and park-unpark.  The monitor subsystem
 202 //   manages all RUNNING->BLOCKED and BLOCKED->READY transitions while the
 203 //   underlying OS manages the READY<->RUN transitions.
 204 //
 205 // * Waiting threads reside on the WaitSet list -- wait() puts
 206 //   the caller onto the WaitSet.
 207 //
 208 // * notify() or notifyAll() simply transfers threads from the WaitSet to
 209 //   either the EntryList or cxq.  Subsequent exit() operations will
 210 //   unpark the notifyee.  Unparking a notifee in notify() is inefficient -
 211 //   it's likely the notifyee would simply impale itself on the lock held
 212 //   by the notifier.
 213 //
 214 // * An interesting alternative is to encode cxq as (List,LockByte) where
 215 //   the LockByte is 0 iff the monitor is owned.  _owner is simply an auxiliary
 216 //   variable, like _recursions, in the scheme.  The threads or Events that form
 217 //   the list would have to be aligned in 256-byte addresses.  A thread would
 218 //   try to acquire the lock or enqueue itself with CAS, but exiting threads
 219 //   could use a 1-0 protocol and simply STB to set the LockByte to 0.
 220 //   Note that is is *not* word-tearing, but it does presume that full-word
 221 //   CAS operations are coherent with intermix with STB operations.  That's true
 222 //   on most common processors.
 223 //
 224 // * See also http://blogs.sun.com/dave
 225 
 226 
 227 // Check that object() and set_object() are called from the right context:
 228 static void check_object_context() {
 229 #ifdef ASSERT
 230   Thread* self = Thread::current();
 231   if (self->is_Java_thread()) {
 232     // Mostly called from JavaThreads so sanity check the thread state.
 233     JavaThread* jt = JavaThread::cast(self);
 234     switch (jt->thread_state()) {
 235     case _thread_in_vm:    // the usual case
 236     case _thread_in_Java:  // during deopt
 237       break;
 238     default:
 239       fatal("called from an unsafe thread state");
 240     }
 241     assert(jt->is_active_Java_thread(), "must be active JavaThread");
 242   } else {
 243     // However, ThreadService::get_current_contended_monitor()
 244     // can call here via the VMThread so sanity check it.
 245     assert(self->is_VM_thread(), "must be");
 246   }
 247 #endif // ASSERT
 248 }
 249 
 250 ObjectMonitor::ObjectMonitor(oop object) :
 251   _metadata(0),
 252   _object(_oop_storage, object),
 253   _owner(nullptr),

 254   _previous_owner_tid(0),
 255   _next_om(nullptr),
 256   _recursions(0),
 257   _EntryList(nullptr),
 258   _cxq(nullptr),
 259   _succ(nullptr),
 260   _Responsible(nullptr),
 261   _SpinDuration(ObjectMonitor::Knob_SpinLimit),
 262   _contentions(0),
 263   _WaitSet(nullptr),
 264   _waiters(0),
 265   _WaitSetLock(0)
 266 { }
 267 
 268 ObjectMonitor::~ObjectMonitor() {
 269   _object.release(_oop_storage);
 270 }
 271 
 272 oop ObjectMonitor::object() const {
 273   check_object_context();
 274   return _object.resolve();
 275 }
 276 
 277 void ObjectMonitor::ExitOnSuspend::operator()(JavaThread* current) {
 278   if (current->is_suspended()) {
 279     _om->_recursions = 0;
 280     _om->_succ = nullptr;
 281     // Don't need a full fence after clearing successor here because of the call to exit().
 282     _om->exit(current, false /* not_suspended */);
 283     _om_exited = true;
 284 
 285     current->set_current_pending_monitor(_om);
 286   }
 287 }
 288 
 289 void ObjectMonitor::ClearSuccOnSuspend::operator()(JavaThread* current) {
 290   if (current->is_suspended()) {
 291     if (_om->_succ == current) {
 292       _om->_succ = nullptr;
 293       OrderAccess::fence(); // always do a full fence when successor is cleared
 294     }
 295   }
 296 }
 297 
 298 #define assert_mark_word_consistency()                                         \
 299   assert(UseObjectMonitorTable || object()->mark() == markWord::encode(this),  \
 300          "object mark must match encoded this: mark=" INTPTR_FORMAT            \
 301          ", encoded this=" INTPTR_FORMAT, object()->mark().value(),            \
 302          markWord::encode(this).value());
 303 
 304 // -----------------------------------------------------------------------------
 305 // Enter support
 306 
 307 bool ObjectMonitor::enter_is_async_deflating() {
 308   if (is_being_async_deflated()) {
 309     if (!UseObjectMonitorTable) {
 310       const oop l_object = object();
 311       if (l_object != nullptr) {
 312         // Attempt to restore the header/dmw to the object's header so that
 313         // we only retry once if the deflater thread happens to be slow.
 314         install_displaced_markword_in_object(l_object);
 315       }
 316     }
 317     return true;
 318   }
 319 
 320   return false;
 321 }
 322 
 323 void ObjectMonitor::enter_for_with_contention_mark(JavaThread* locking_thread, ObjectMonitorContentionMark& contention_mark) {
 324   // Used by ObjectSynchronizer::enter_for to enter for another thread.
 325   // The monitor is private to or already owned by locking_thread which must be suspended.
 326   // So this code may only contend with deflation.
 327   assert(locking_thread == Thread::current() || locking_thread->is_obj_deopt_suspend(), "must be");
 328   assert(contention_mark._monitor == this, "must be");
 329   assert(!is_being_async_deflated(), "must be");
 330 
 331 
 332   void* prev_owner = try_set_owner_from(nullptr, locking_thread);
 333 
 334   bool success = false;
 335 
 336   if (prev_owner == nullptr) {
 337     assert(_recursions == 0, "invariant");
 338     success = true;
 339   } else if (prev_owner == locking_thread) {
 340     _recursions++;
 341     success = true;
 342   } else if (prev_owner == DEFLATER_MARKER) {
 343     // Racing with deflation.
 344     prev_owner = try_set_owner_from(DEFLATER_MARKER, locking_thread);
 345     if (prev_owner == DEFLATER_MARKER) {
 346       // Cancelled deflation. Increment contentions as part of the deflation protocol.
 347       add_to_contentions(1);
 348       success = true;
 349     } else if (prev_owner == nullptr) {
 350       // At this point we cannot race with deflation as we have both incremented
 351       // contentions, seen contention > 0 and seen a DEFLATER_MARKER.
 352       // success will only be false if this races with something other than
 353       // deflation.
 354       prev_owner = try_set_owner_from(nullptr, locking_thread);
 355       success = prev_owner == nullptr;
 356     }
 357   } else if (LockingMode == LM_LEGACY && locking_thread->is_lock_owned((address)prev_owner)) {
 358     assert(_recursions == 0, "must be");
 359     _recursions = 1;
 360     set_owner_from_BasicLock(prev_owner, locking_thread);
 361     success = true;
 362   }
 363   assert(success, "Failed to enter_for: locking_thread=" INTPTR_FORMAT
 364           ", this=" INTPTR_FORMAT "{owner=" INTPTR_FORMAT "}, observed owner: " INTPTR_FORMAT,
 365           p2i(locking_thread), p2i(this), p2i(owner_raw()), p2i(prev_owner));
 366 }
 367 
 368 bool ObjectMonitor::enter_for(JavaThread* locking_thread) {
 369 
 370   // Block out deflation as soon as possible.
 371   ObjectMonitorContentionMark contention_mark(this);
 372 
 373   // Check for deflation.
 374   if (enter_is_async_deflating()) {
 375     return false;
 376   }
 377 
 378   enter_for_with_contention_mark(locking_thread, contention_mark);
 379   assert(owner_raw() == locking_thread, "must be");
 380   return true;
 381 }
 382 
 383 bool ObjectMonitor::try_enter(JavaThread* current) {
 384   // TryLock avoids the CAS
 385   TryLockResult r = TryLock(current);
 386   if (r == TryLockResult::Success) {
 387     assert(_recursions == 0, "invariant");
 388     return true;
 389   }
 390 
 391   if (r == TryLockResult::HasOwner && owner() == current) {
 392     _recursions++;
 393     return true;
 394   }
 395 
 396   void* cur = owner_raw();
 397   if (LockingMode == LM_LEGACY && current->is_lock_owned((address)cur)) {
 398     assert(_recursions == 0, "internal state error");
 399     _recursions = 1;
 400     set_owner_from_BasicLock(cur, current);  // Convert from BasicLock* to Thread*.
 401     return true;
 402   }
 403 
 404   return false;
 405 }
 406 
 407 bool ObjectMonitor::spin_enter(JavaThread* current) {
 408   assert(current == JavaThread::current(), "must be");
 409 
 410   // Check for recursion.
 411   if (try_enter(current)) {
 412     return true;
 413   }
 414 
 415   // Check for deflation.
 416   if (enter_is_async_deflating()) {
 417     return false;
 418   }
 419 
 420   // We've encountered genuine contention.
 421 
 422   // Do one round of spinning.
 423   // Note that if we acquire the monitor from an initial spin
 424   // we forgo posting JVMTI events and firing DTRACE probes.
 425   if (TrySpin(current)) {
 426     assert(owner_raw() == current, "must be current: owner=" INTPTR_FORMAT, p2i(owner_raw()));
 427     assert(_recursions == 0, "must be 0: recursions=" INTX_FORMAT, _recursions);
 428     assert_mark_word_consistency();
 429     return true;
 430   }
 431 
 432   return false;
 433 }
 434 
 435 bool ObjectMonitor::enter(JavaThread* current) {
 436   assert(current == JavaThread::current(), "must be");
 437 
 438   if (spin_enter(current)) {
 439     return true;
 440   }
 441 
 442   assert(owner_raw() != current, "invariant");
 443   assert(_succ != current, "invariant");
 444   assert(!SafepointSynchronize::is_at_safepoint(), "invariant");
 445   assert(current->thread_state() != _thread_blocked, "invariant");
 446 
 447   // Keep is_being_async_deflated stable across the rest of enter
 448   ObjectMonitorContentionMark contention_mark(this);
 449 
 450   // Check for deflation.
 451   if (enter_is_async_deflating()) {
 452     return false;
 453   }
 454 
 455   // At this point this ObjectMonitor cannot be deflated, finish contended enter
 456   enter_with_contention_mark(current, contention_mark);
 457   return true;
 458 }
 459 
 460 void ObjectMonitor::enter_with_contention_mark(JavaThread *current, ObjectMonitorContentionMark &cm) {
 461   assert(current == JavaThread::current(), "must be");
 462   assert(owner_raw() != current, "must be");
 463   assert(cm._monitor == this, "must be");
 464   assert(!is_being_async_deflated(), "must be");
 465 
 466   JFR_ONLY(JfrConditionalFlush<EventJavaMonitorEnter> flush(current);)
 467   EventJavaMonitorEnter event;
 468   if (event.is_started()) {
 469     event.set_monitorClass(object()->klass());
 470     // Set an address that is 'unique enough', such that events close in
 471     // time and with the same address are likely (but not guaranteed) to
 472     // belong to the same object.
 473     event.set_address((uintptr_t)this);
 474   }
 475 
 476   { // Change java thread status to indicate blocked on monitor enter.
 477     JavaThreadBlockedOnMonitorEnterState jtbmes(current, this);
 478 
 479     assert(current->current_pending_monitor() == nullptr, "invariant");
 480     current->set_current_pending_monitor(this);
 481 
 482     DTRACE_MONITOR_PROBE(contended__enter, this, object(), current);
 483     if (JvmtiExport::should_post_monitor_contended_enter()) {
 484       JvmtiExport::post_monitor_contended_enter(current, this);
 485 
 486       // The current thread does not yet own the monitor and does not
 487       // yet appear on any queues that would get it made the successor.
 488       // This means that the JVMTI_EVENT_MONITOR_CONTENDED_ENTER event
 489       // handler cannot accidentally consume an unpark() meant for the
 490       // ParkEvent associated with this ObjectMonitor.
 491     }
 492 


























 493     OSThreadContendState osts(current->osthread());
 494 
 495     assert(current->thread_state() == _thread_in_vm, "invariant");
 496 
 497     for (;;) {
 498       ExitOnSuspend eos(this);
 499       {
 500         ThreadBlockInVMPreprocess<ExitOnSuspend> tbivs(current, eos, true /* allow_suspend */);
 501         EnterI(current);
 502         current->set_current_pending_monitor(nullptr);
 503         // We can go to a safepoint at the end of this block. If we
 504         // do a thread dump during that safepoint, then this thread will show
 505         // as having "-locked" the monitor, but the OS and java.lang.Thread
 506         // states will still report that the thread is blocked trying to
 507         // acquire it.
 508         // If there is a suspend request, ExitOnSuspend will exit the OM
 509         // and set the OM as pending.
 510       }
 511       if (!eos.exited()) {
 512         // ExitOnSuspend did not exit the OM
 513         assert(owner_raw() == current, "invariant");
 514         break;
 515       }
 516     }
 517 
 518     // We've just gotten past the enter-check-for-suspend dance and we now own
 519     // the monitor free and clear.
 520   }
 521 
 522   assert(contentions() >= 0, "must not be negative: contentions=%d", contentions());
 523 
 524   // Must either set _recursions = 0 or ASSERT _recursions == 0.
 525   assert(_recursions == 0, "invariant");
 526   assert(owner_raw() == current, "invariant");
 527   assert(_succ != current, "invariant");
 528   assert_mark_word_consistency();
 529 
 530   // The thread -- now the owner -- is back in vm mode.
 531   // Report the glorious news via TI,DTrace and jvmstat.
 532   // The probe effect is non-trivial.  All the reportage occurs
 533   // while we hold the monitor, increasing the length of the critical
 534   // section.  Amdahl's parallel speedup law comes vividly into play.
 535   //
 536   // Another option might be to aggregate the events (thread local or
 537   // per-monitor aggregation) and defer reporting until a more opportune
 538   // time -- such as next time some thread encounters contention but has
 539   // yet to acquire the lock.  While spinning that thread could
 540   // spinning we could increment JVMStat counters, etc.
 541 
 542   DTRACE_MONITOR_PROBE(contended__entered, this, object(), current);
 543   if (JvmtiExport::should_post_monitor_contended_entered()) {
 544     JvmtiExport::post_monitor_contended_entered(current, this);
 545 
 546     // The current thread already owns the monitor and is not going to
 547     // call park() for the remainder of the monitor enter protocol. So
 548     // it doesn't matter if the JVMTI_EVENT_MONITOR_CONTENDED_ENTERED
 549     // event handler consumed an unpark() issued by the thread that
 550     // just exited the monitor.
 551   }
 552   if (event.should_commit()) {
 553     event.set_previousOwner(_previous_owner_tid);
 554     event.commit();
 555   }
 556   OM_PERFDATA_OP(ContendedLockAttempts, inc());
 557 }
 558 
 559 // Caveat: TryLock() is not necessarily serializing if it returns failure.
 560 // Callers must compensate as needed.
 561 
 562 ObjectMonitor::TryLockResult ObjectMonitor::TryLock(JavaThread* current) {
 563   void* own = owner_raw();
 564   if (own != nullptr) return TryLockResult::HasOwner;
 565   if (try_set_owner_from(nullptr, current) == nullptr) {
 566     assert(_recursions == 0, "invariant");
 567     return TryLockResult::Success;
 568   }
 569   // The lock had been free momentarily, but we lost the race to the lock.
 570   // Interference -- the CAS failed.
 571   // We can either return -1 or retry.
 572   // Retry doesn't make as much sense because the lock was just acquired.
 573   return TryLockResult::Interference;
 574 }
 575 
 576 // Deflate the specified ObjectMonitor if not in-use. Returns true if it
 577 // was deflated and false otherwise.
 578 //
 579 // The async deflation protocol sets owner to DEFLATER_MARKER and
 580 // makes contentions negative as signals to contending threads that
 581 // an async deflation is in progress. There are a number of checks
 582 // as part of the protocol to make sure that the calling thread has
 583 // not lost the race to a contending thread.
 584 //
 585 // The ObjectMonitor has been successfully async deflated when:
 586 //   (contentions < 0)
 587 // Contending threads that see that condition know to retry their operation.
 588 //
 589 bool ObjectMonitor::deflate_monitor(Thread* current) {
 590   if (is_busy()) {
 591     // Easy checks are first - the ObjectMonitor is busy so no deflation.
 592     return false;
 593   }
 594 
 595   const oop obj = object_peek();
 596 
 597   if (obj == nullptr) {
 598     // If the object died, we can recycle the monitor without racing with
 599     // Java threads. The GC already broke the association with the object.
 600     set_owner_from(nullptr, DEFLATER_MARKER);
 601     assert(contentions() >= 0, "must be non-negative: contentions=%d", contentions());
 602     _contentions = INT_MIN; // minimum negative int
 603   } else {
 604     // Attempt async deflation protocol.
 605 
 606     // Set a null owner to DEFLATER_MARKER to force any contending thread
 607     // through the slow path. This is just the first part of the async
 608     // deflation dance.
 609     if (try_set_owner_from(nullptr, DEFLATER_MARKER) != nullptr) {
 610       // The owner field is no longer null so we lost the race since the
 611       // ObjectMonitor is now busy.
 612       return false;
 613     }
 614 
 615     if (contentions() > 0 || _waiters != 0) {
 616       // Another thread has raced to enter the ObjectMonitor after
 617       // is_busy() above or has already entered and waited on
 618       // it which makes it busy so no deflation. Restore owner to
 619       // null if it is still DEFLATER_MARKER.
 620       if (try_set_owner_from(DEFLATER_MARKER, nullptr) != DEFLATER_MARKER) {
 621         // Deferred decrement for the JT EnterI() that cancelled the async deflation.
 622         add_to_contentions(-1);
 623       }
 624       return false;
 625     }
 626 
 627     // Make a zero contentions field negative to force any contending threads
 628     // to retry. This is the second part of the async deflation dance.
 629     if (Atomic::cmpxchg(&_contentions, 0, INT_MIN) != 0) {
 630       // Contentions was no longer 0 so we lost the race since the
 631       // ObjectMonitor is now busy. Restore owner to null if it is
 632       // still DEFLATER_MARKER:
 633       if (try_set_owner_from(DEFLATER_MARKER, nullptr) != DEFLATER_MARKER) {
 634         // Deferred decrement for the JT EnterI() that cancelled the async deflation.
 635         add_to_contentions(-1);
 636       }
 637       return false;
 638     }
 639   }
 640 
 641   // Sanity checks for the races:
 642   guarantee(owner_is_DEFLATER_MARKER(), "must be deflater marker");
 643   guarantee(contentions() < 0, "must be negative: contentions=%d",
 644             contentions());
 645   guarantee(_waiters == 0, "must be 0: waiters=%d", _waiters);
 646   guarantee(_cxq == nullptr, "must be no contending threads: cxq="
 647             INTPTR_FORMAT, p2i(_cxq));
 648   guarantee(_EntryList == nullptr,
 649             "must be no entering threads: EntryList=" INTPTR_FORMAT,
 650             p2i(_EntryList));
 651 
 652   if (obj != nullptr) {
 653     if (log_is_enabled(Trace, monitorinflation)) {
 654       ResourceMark rm;
 655       log_trace(monitorinflation)("deflate_monitor: object=" INTPTR_FORMAT
 656                                   ", mark=" INTPTR_FORMAT ", type='%s'",
 657                                   p2i(obj), obj->mark().value(),
 658                                   obj->klass()->external_name());
 659     }
 660   }
 661 
 662   if (UseObjectMonitorTable) {
 663     LightweightSynchronizer::deflate_monitor(current, obj, this);
 664   } else if (obj != nullptr) {
 665     // Install the old mark word if nobody else has already done it.
 666     install_displaced_markword_in_object(obj);
 667   }
 668 
 669   // We leave owner == DEFLATER_MARKER and contentions < 0
 670   // to force any racing threads to retry.
 671   return true;  // Success, ObjectMonitor has been deflated.
 672 }
 673 
 674 // Install the displaced mark word (dmw) of a deflating ObjectMonitor
 675 // into the header of the object associated with the monitor. This
 676 // idempotent method is called by a thread that is deflating a
 677 // monitor and by other threads that have detected a race with the
 678 // deflation process.
 679 void ObjectMonitor::install_displaced_markword_in_object(const oop obj) {
 680   assert(!UseObjectMonitorTable, "ObjectMonitorTable has no dmw");
 681   // This function must only be called when (owner == DEFLATER_MARKER
 682   // && contentions <= 0), but we can't guarantee that here because
 683   // those values could change when the ObjectMonitor gets moved from
 684   // the global free list to a per-thread free list.
 685 
 686   guarantee(obj != nullptr, "must be non-null");
 687 
 688   // Separate loads in is_being_async_deflated(), which is almost always
 689   // called before this function, from the load of dmw/header below.
 690 
 691   // _contentions and dmw/header may get written by different threads.
 692   // Make sure to observe them in the same order when having several observers.
 693   OrderAccess::loadload_for_IRIW();
 694 
 695   const oop l_object = object_peek();
 696   if (l_object == nullptr) {
 697     // ObjectMonitor's object ref has already been cleared by async
 698     // deflation or GC so we're done here.
 699     return;
 700   }
 701   assert(l_object == obj, "object=" INTPTR_FORMAT " must equal obj="
 702          INTPTR_FORMAT, p2i(l_object), p2i(obj));
 703 
 704   markWord dmw = header();
 705   // The dmw has to be neutral (not null, not locked and not marked).
 706   assert(dmw.is_neutral(), "must be neutral: dmw=" INTPTR_FORMAT, dmw.value());
 707 
 708   // Install displaced mark word if the object's header still points
 709   // to this ObjectMonitor. More than one racing caller to this function
 710   // can rarely reach this point, but only one can win.
 711   markWord res = obj->cas_set_mark(dmw, markWord::encode(this));
 712   if (res != markWord::encode(this)) {
 713     // This should be rare so log at the Info level when it happens.
 714     log_info(monitorinflation)("install_displaced_markword_in_object: "
 715                                "failed cas_set_mark: new_mark=" INTPTR_FORMAT
 716                                ", old_mark=" INTPTR_FORMAT ", res=" INTPTR_FORMAT,
 717                                dmw.value(), markWord::encode(this).value(),
 718                                res.value());
 719   }
 720 
 721   // Note: It does not matter which thread restored the header/dmw
 722   // into the object's header. The thread deflating the monitor just
 723   // wanted the object's header restored and it is. The threads that
 724   // detected a race with the deflation process also wanted the
 725   // object's header restored before they retry their operation and
 726   // because it is restored they will only retry once.
 727 }
 728 
 729 // Convert the fields used by is_busy() to a string that can be
 730 // used for diagnostic output.
 731 const char* ObjectMonitor::is_busy_to_string(stringStream* ss) {
 732   ss->print("is_busy: waiters=%d"
 733             ", contentions=%d"
 734             ", owner=" PTR_FORMAT
 735             ", cxq=" PTR_FORMAT
 736             ", EntryList=" PTR_FORMAT,
 737             _waiters,
 738             (contentions() > 0 ? contentions() : 0),
 739             owner_is_DEFLATER_MARKER()
 740                 // We report null instead of DEFLATER_MARKER here because is_busy()
 741                 // ignores DEFLATER_MARKER values.
 742                 ? p2i(nullptr)
 743                 : p2i(owner_raw()),
 744             p2i(_cxq),
 745             p2i(_EntryList));
 746   return ss->base();
 747 }
 748 
 749 #define MAX_RECHECK_INTERVAL 1000
 750 
 751 void ObjectMonitor::EnterI(JavaThread* current) {
 752   assert(current->thread_state() == _thread_blocked, "invariant");
 753 
 754   // Try the lock - TATAS
 755   if (TryLock(current) == TryLockResult::Success) {
 756     assert(_succ != current, "invariant");
 757     assert(owner_raw() == current, "invariant");
 758     assert(_Responsible != current, "invariant");
 759     return;
 760   }
 761 
 762   if (try_set_owner_from(DEFLATER_MARKER, current) == DEFLATER_MARKER) {
 763     // Cancelled the in-progress async deflation by changing owner from
 764     // DEFLATER_MARKER to current. As part of the contended enter protocol,
 765     // contentions was incremented to a positive value before EnterI()
 766     // was called and that prevents the deflater thread from winning the
 767     // last part of the 2-part async deflation protocol. After EnterI()
 768     // returns to enter(), contentions is decremented because the caller
 769     // now owns the monitor. We bump contentions an extra time here to
 770     // prevent the deflater thread from winning the last part of the
 771     // 2-part async deflation protocol after the regular decrement
 772     // occurs in enter(). The deflater thread will decrement contentions
 773     // after it recognizes that the async deflation was cancelled.
 774     add_to_contentions(1);
 775     assert(_succ != current, "invariant");
 776     assert(_Responsible != current, "invariant");
 777     return;
 778   }
 779 
 780   assert(InitDone, "Unexpectedly not initialized");
 781 
 782   // We try one round of spinning *before* enqueueing current.
 783   //
 784   // If the _owner is ready but OFFPROC we could use a YieldTo()
 785   // operation to donate the remainder of this thread's quantum
 786   // to the owner.  This has subtle but beneficial affinity
 787   // effects.
 788 
 789   if (TrySpin(current)) {
 790     assert(owner_raw() == current, "invariant");
 791     assert(_succ != current, "invariant");
 792     assert(_Responsible != current, "invariant");
 793     return;
 794   }
 795 
 796   // The Spin failed -- Enqueue and park the thread ...
 797   assert(_succ != current, "invariant");
 798   assert(owner_raw() != current, "invariant");
 799   assert(_Responsible != current, "invariant");
 800 
 801   // Enqueue "current" on ObjectMonitor's _cxq.
 802   //
 803   // Node acts as a proxy for current.
 804   // As an aside, if were to ever rewrite the synchronization code mostly
 805   // in Java, WaitNodes, ObjectMonitors, and Events would become 1st-class
 806   // Java objects.  This would avoid awkward lifecycle and liveness issues,
 807   // as well as eliminate a subset of ABA issues.
 808   // TODO: eliminate ObjectWaiter and enqueue either Threads or Events.
 809 
 810   ObjectWaiter node(current);
 811   current->_ParkEvent->reset();
 812   node._prev   = (ObjectWaiter*) 0xBAD;
 813   node.TState  = ObjectWaiter::TS_CXQ;
 814 
 815   // Push "current" onto the front of the _cxq.
 816   // Once on cxq/EntryList, current stays on-queue until it acquires the lock.
 817   // Note that spinning tends to reduce the rate at which threads
 818   // enqueue and dequeue on EntryList|cxq.
 819   ObjectWaiter* nxt;
 820   for (;;) {
 821     node._next = nxt = _cxq;
 822     if (Atomic::cmpxchg(&_cxq, nxt, &node) == nxt) break;
 823 
 824     // Interference - the CAS failed because _cxq changed.  Just retry.
 825     // As an optional optimization we retry the lock.
 826     if (TryLock(current) == TryLockResult::Success) {
 827       assert(_succ != current, "invariant");
 828       assert(owner_raw() == current, "invariant");
 829       assert(_Responsible != current, "invariant");
 830       return;
 831     }
 832   }
 833 
 834   // Check for cxq|EntryList edge transition to non-null.  This indicates
 835   // the onset of contention.  While contention persists exiting threads
 836   // will use a ST:MEMBAR:LD 1-1 exit protocol.  When contention abates exit
 837   // operations revert to the faster 1-0 mode.  This enter operation may interleave
 838   // (race) a concurrent 1-0 exit operation, resulting in stranding, so we
 839   // arrange for one of the contending thread to use a timed park() operations
 840   // to detect and recover from the race.  (Stranding is form of progress failure
 841   // where the monitor is unlocked but all the contending threads remain parked).
 842   // That is, at least one of the contended threads will periodically poll _owner.
 843   // One of the contending threads will become the designated "Responsible" thread.
 844   // The Responsible thread uses a timed park instead of a normal indefinite park
 845   // operation -- it periodically wakes and checks for and recovers from potential
 846   // strandings admitted by 1-0 exit operations.   We need at most one Responsible
 847   // thread per-monitor at any given moment.  Only threads on cxq|EntryList may
 848   // be responsible for a monitor.
 849   //
 850   // Currently, one of the contended threads takes on the added role of "Responsible".
 851   // A viable alternative would be to use a dedicated "stranding checker" thread
 852   // that periodically iterated over all the threads (or active monitors) and unparked
 853   // successors where there was risk of stranding.  This would help eliminate the
 854   // timer scalability issues we see on some platforms as we'd only have one thread
 855   // -- the checker -- parked on a timer.
 856 
 857   if (nxt == nullptr && _EntryList == nullptr) {
 858     // Try to assume the role of responsible thread for the monitor.
 859     // CONSIDER:  ST vs CAS vs { if (Responsible==null) Responsible=current }
 860     Atomic::replace_if_null(&_Responsible, current);
 861   }
 862 
 863   // The lock might have been released while this thread was occupied queueing
 864   // itself onto _cxq.  To close the race and avoid "stranding" and
 865   // progress-liveness failure we must resample-retry _owner before parking.
 866   // Note the Dekker/Lamport duality: ST cxq; MEMBAR; LD Owner.
 867   // In this case the ST-MEMBAR is accomplished with CAS().
 868   //
 869   // TODO: Defer all thread state transitions until park-time.
 870   // Since state transitions are heavy and inefficient we'd like
 871   // to defer the state transitions until absolutely necessary,
 872   // and in doing so avoid some transitions ...
 873 
 874   int recheckInterval = 1;






 875 
 876   for (;;) {
 877 
 878     if (TryLock(current) == TryLockResult::Success) {
 879       break;
 880     }
 881     assert(owner_raw() != current, "invariant");
 882 
 883     // park self
 884     if (_Responsible == current) {
 885       current->_ParkEvent->park((jlong) recheckInterval);
 886       // Increase the recheckInterval, but clamp the value.
 887       recheckInterval *= 8;
 888       if (recheckInterval > MAX_RECHECK_INTERVAL) {
 889         recheckInterval = MAX_RECHECK_INTERVAL;
 890       }
 891     } else {
 892       current->_ParkEvent->park();
 893     }
 894 
 895     if (TryLock(current) == TryLockResult::Success) {
 896       break;
 897     }
 898 
 899     if (try_set_owner_from(DEFLATER_MARKER, current) == DEFLATER_MARKER) {
 900       // Cancelled the in-progress async deflation by changing owner from
 901       // DEFLATER_MARKER to current. As part of the contended enter protocol,
 902       // contentions was incremented to a positive value before EnterI()
 903       // was called and that prevents the deflater thread from winning the
 904       // last part of the 2-part async deflation protocol. After EnterI()
 905       // returns to enter(), contentions is decremented because the caller
 906       // now owns the monitor. We bump contentions an extra time here to
 907       // prevent the deflater thread from winning the last part of the
 908       // 2-part async deflation protocol after the regular decrement
 909       // occurs in enter(). The deflater thread will decrement contentions
 910       // after it recognizes that the async deflation was cancelled.
 911       add_to_contentions(1);
 912       break;
 913     }
 914 
 915     // The lock is still contested.
 916 
 917     // Keep a tally of the # of futile wakeups.
 918     // Note that the counter is not protected by a lock or updated by atomics.
 919     // That is by design - we trade "lossy" counters which are exposed to
 920     // races during updates for a lower probe effect.
 921     // This PerfData object can be used in parallel with a safepoint.
 922     // See the work around in PerfDataManager::destroy().
 923     OM_PERFDATA_OP(FutileWakeups, inc());
 924 
 925     // Assuming this is not a spurious wakeup we'll normally find _succ == current.
 926     // We can defer clearing _succ until after the spin completes
 927     // TrySpin() must tolerate being called with _succ == current.
 928     // Try yet another round of adaptive spinning.
 929     if (TrySpin(current)) {
 930       break;
 931     }
 932 
 933     // We can find that we were unpark()ed and redesignated _succ while
 934     // we were spinning.  That's harmless.  If we iterate and call park(),
 935     // park() will consume the event and return immediately and we'll
 936     // just spin again.  This pattern can repeat, leaving _succ to simply
 937     // spin on a CPU.
 938 
 939     if (_succ == current) _succ = nullptr;
 940 
 941     // Invariant: after clearing _succ a thread *must* retry _owner before parking.
 942     OrderAccess::fence();
 943   }
 944 
 945   // Egress :
 946   // current has acquired the lock -- Unlink current from the cxq or EntryList.
 947   // Normally we'll find current on the EntryList .
 948   // From the perspective of the lock owner (this thread), the
 949   // EntryList is stable and cxq is prepend-only.
 950   // The head of cxq is volatile but the interior is stable.
 951   // In addition, current.TState is stable.
 952 
 953   assert(owner_raw() == current, "invariant");
 954 
 955   UnlinkAfterAcquire(current, &node);
 956   if (_succ == current) _succ = nullptr;
 957 
 958   assert(_succ != current, "invariant");
 959   if (_Responsible == current) {
 960     _Responsible = nullptr;
 961     OrderAccess::fence(); // Dekker pivot-point
 962 
 963     // We may leave threads on cxq|EntryList without a designated
 964     // "Responsible" thread.  This is benign.  When this thread subsequently
 965     // exits the monitor it can "see" such preexisting "old" threads --
 966     // threads that arrived on the cxq|EntryList before the fence, above --
 967     // by LDing cxq|EntryList.  Newly arrived threads -- that is, threads
 968     // that arrive on cxq after the ST:MEMBAR, above -- will set Responsible
 969     // non-null and elect a new "Responsible" timer thread.
 970     //
 971     // This thread executes:
 972     //    ST Responsible=null; MEMBAR    (in enter epilogue - here)
 973     //    LD cxq|EntryList               (in subsequent exit)
 974     //
 975     // Entering threads in the slow/contended path execute:
 976     //    ST cxq=nonnull; MEMBAR; LD Responsible (in enter prolog)
 977     //    The (ST cxq; MEMBAR) is accomplished with CAS().
 978     //
 979     // The MEMBAR, above, prevents the LD of cxq|EntryList in the subsequent
 980     // exit operation from floating above the ST Responsible=null.
 981   }
 982 
 983   // We've acquired ownership with CAS().
 984   // CAS is serializing -- it has MEMBAR/FENCE-equivalent semantics.
 985   // But since the CAS() this thread may have also stored into _succ,
 986   // EntryList, cxq or Responsible.  These meta-data updates must be
 987   // visible __before this thread subsequently drops the lock.
 988   // Consider what could occur if we didn't enforce this constraint --
 989   // STs to monitor meta-data and user-data could reorder with (become
 990   // visible after) the ST in exit that drops ownership of the lock.
 991   // Some other thread could then acquire the lock, but observe inconsistent
 992   // or old monitor meta-data and heap data.  That violates the JMM.
 993   // To that end, the 1-0 exit() operation must have at least STST|LDST
 994   // "release" barrier semantics.  Specifically, there must be at least a
 995   // STST|LDST barrier in exit() before the ST of null into _owner that drops
 996   // the lock.   The barrier ensures that changes to monitor meta-data and data
 997   // protected by the lock will be visible before we release the lock, and
 998   // therefore before some other thread (CPU) has a chance to acquire the lock.
 999   // See also: http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
1000   //
1001   // Critically, any prior STs to _succ or EntryList must be visible before
1002   // the ST of null into _owner in the *subsequent* (following) corresponding
1003   // monitorexit.  Recall too, that in 1-0 mode monitorexit does not necessarily
1004   // execute a serializing instruction.
1005 
1006   return;
1007 }
1008 
1009 // ReenterI() is a specialized inline form of the latter half of the
1010 // contended slow-path from EnterI().  We use ReenterI() only for
1011 // monitor reentry in wait().
1012 //
1013 // In the future we should reconcile EnterI() and ReenterI().
1014 
1015 void ObjectMonitor::ReenterI(JavaThread* current, ObjectWaiter* currentNode) {
1016   assert(current != nullptr, "invariant");
1017   assert(current->thread_state() != _thread_blocked, "invariant");
1018   assert(currentNode != nullptr, "invariant");
1019   assert(currentNode->_thread == current, "invariant");
1020   assert(_waiters > 0, "invariant");
1021   assert_mark_word_consistency();
1022 
1023   for (;;) {
1024     ObjectWaiter::TStates v = currentNode->TState;
1025     guarantee(v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant");
1026     assert(owner_raw() != current, "invariant");
1027 
1028     // This thread has been notified so try to reacquire the lock.
1029     if (TryLock(current) == TryLockResult::Success) {
1030       break;
1031     }
1032 
1033     // If that fails, spin again.  Note that spin count may be zero so the above TryLock
1034     // is necessary.
1035     if (TrySpin(current)) {
1036         break;
1037     }
1038 
1039     {
1040       OSThreadContendState osts(current->osthread());
1041 
1042       assert(current->thread_state() == _thread_in_vm, "invariant");
1043 
1044       {
1045         ClearSuccOnSuspend csos(this);
1046         ThreadBlockInVMPreprocess<ClearSuccOnSuspend> tbivs(current, csos, true /* allow_suspend */);
1047         current->_ParkEvent->park();
1048       }
1049     }
1050 
1051     // Try again, but just so we distinguish between futile wakeups and
1052     // successful wakeups.  The following test isn't algorithmically
1053     // necessary, but it helps us maintain sensible statistics.
1054     if (TryLock(current) == TryLockResult::Success) {
1055       break;
1056     }
1057 
1058     // The lock is still contested.
1059 
1060     // Assuming this is not a spurious wakeup we'll normally
1061     // find that _succ == current.
1062     if (_succ == current) _succ = nullptr;
1063 
1064     // Invariant: after clearing _succ a contending thread
1065     // *must* retry  _owner before parking.
1066     OrderAccess::fence();
1067 
1068     // Keep a tally of the # of futile wakeups.
1069     // Note that the counter is not protected by a lock or updated by atomics.
1070     // That is by design - we trade "lossy" counters which are exposed to
1071     // races during updates for a lower probe effect.
1072     // This PerfData object can be used in parallel with a safepoint.
1073     // See the work around in PerfDataManager::destroy().
1074     OM_PERFDATA_OP(FutileWakeups, inc());
1075   }
1076 
1077   // current has acquired the lock -- Unlink current from the cxq or EntryList .
1078   // Normally we'll find current on the EntryList.
1079   // Unlinking from the EntryList is constant-time and atomic-free.
1080   // From the perspective of the lock owner (this thread), the
1081   // EntryList is stable and cxq is prepend-only.
1082   // The head of cxq is volatile but the interior is stable.
1083   // In addition, current.TState is stable.
1084 
1085   assert(owner_raw() == current, "invariant");
1086   assert_mark_word_consistency();
1087   UnlinkAfterAcquire(current, currentNode);
1088   if (_succ == current) _succ = nullptr;
1089   assert(_succ != current, "invariant");
1090   currentNode->TState = ObjectWaiter::TS_RUN;
1091   OrderAccess::fence();      // see comments at the end of EnterI()
1092 }
1093 





















































































































































































1094 // By convention we unlink a contending thread from EntryList|cxq immediately
1095 // after the thread acquires the lock in ::enter().  Equally, we could defer
1096 // unlinking the thread until ::exit()-time.
1097 
1098 void ObjectMonitor::UnlinkAfterAcquire(JavaThread* current, ObjectWaiter* currentNode) {
1099   assert(owner_raw() == current, "invariant");
1100   assert(currentNode->_thread == current, "invariant");

1101 
1102   if (currentNode->TState == ObjectWaiter::TS_ENTER) {
1103     // Normal case: remove current from the DLL EntryList .
1104     // This is a constant-time operation.
1105     ObjectWaiter* nxt = currentNode->_next;
1106     ObjectWaiter* prv = currentNode->_prev;
1107     if (nxt != nullptr) nxt->_prev = prv;
1108     if (prv != nullptr) prv->_next = nxt;
1109     if (currentNode == _EntryList) _EntryList = nxt;
1110     assert(nxt == nullptr || nxt->TState == ObjectWaiter::TS_ENTER, "invariant");
1111     assert(prv == nullptr || prv->TState == ObjectWaiter::TS_ENTER, "invariant");
1112   } else {
1113     assert(currentNode->TState == ObjectWaiter::TS_CXQ, "invariant");
1114     // Inopportune interleaving -- current is still on the cxq.
1115     // This usually means the enqueue of self raced an exiting thread.
1116     // Normally we'll find current near the front of the cxq, so
1117     // dequeueing is typically fast.  If needbe we can accelerate
1118     // this with some MCS/CHL-like bidirectional list hints and advisory
1119     // back-links so dequeueing from the interior will normally operate
1120     // in constant-time.
1121     // Dequeue current from either the head (with CAS) or from the interior
1122     // with a linear-time scan and normal non-atomic memory operations.
1123     // CONSIDER: if current is on the cxq then simply drain cxq into EntryList
1124     // and then unlink current from EntryList.  We have to drain eventually,
1125     // so it might as well be now.
1126 
1127     ObjectWaiter* v = _cxq;
1128     assert(v != nullptr, "invariant");
1129     if (v != currentNode || Atomic::cmpxchg(&_cxq, v, currentNode->_next) != v) {
1130       // The CAS above can fail from interference IFF a "RAT" arrived.
1131       // In that case current must be in the interior and can no longer be
1132       // at the head of cxq.
1133       if (v == currentNode) {
1134         assert(_cxq != v, "invariant");
1135         v = _cxq;          // CAS above failed - start scan at head of list
1136       }
1137       ObjectWaiter* p;
1138       ObjectWaiter* q = nullptr;
1139       for (p = v; p != nullptr && p != currentNode; p = p->_next) {
1140         q = p;
1141         assert(p->TState == ObjectWaiter::TS_CXQ, "invariant");
1142       }
1143       assert(v != currentNode, "invariant");
1144       assert(p == currentNode, "Node not found on cxq");
1145       assert(p != _cxq, "invariant");
1146       assert(q != nullptr, "invariant");
1147       assert(q->_next == p, "invariant");
1148       q->_next = p->_next;
1149     }
1150   }
1151 
1152 #ifdef ASSERT
1153   // Diagnostic hygiene ...
1154   currentNode->_prev  = (ObjectWaiter*) 0xBAD;
1155   currentNode->_next  = (ObjectWaiter*) 0xBAD;
1156   currentNode->TState = ObjectWaiter::TS_RUN;
1157 #endif
1158 }
1159 
1160 // -----------------------------------------------------------------------------
1161 // Exit support
1162 //
1163 // exit()
1164 // ~~~~~~
1165 // Note that the collector can't reclaim the objectMonitor or deflate
1166 // the object out from underneath the thread calling ::exit() as the
1167 // thread calling ::exit() never transitions to a stable state.
1168 // This inhibits GC, which in turn inhibits asynchronous (and
1169 // inopportune) reclamation of "this".
1170 //
1171 // We'd like to assert that: (THREAD->thread_state() != _thread_blocked) ;
1172 // There's one exception to the claim above, however.  EnterI() can call
1173 // exit() to drop a lock if the acquirer has been externally suspended.
1174 // In that case exit() is called with _thread_state == _thread_blocked,
1175 // but the monitor's _contentions field is > 0, which inhibits reclamation.
1176 //
1177 // 1-0 exit
1178 // ~~~~~~~~
1179 // ::exit() uses a canonical 1-1 idiom with a MEMBAR although some of
1180 // the fast-path operators have been optimized so the common ::exit()
1181 // operation is 1-0, e.g., see macroAssembler_x86.cpp: fast_unlock().
1182 // The code emitted by fast_unlock() elides the usual MEMBAR.  This
1183 // greatly improves latency -- MEMBAR and CAS having considerable local
1184 // latency on modern processors -- but at the cost of "stranding".  Absent the
1185 // MEMBAR, a thread in fast_unlock() can race a thread in the slow
1186 // ::enter() path, resulting in the entering thread being stranding
1187 // and a progress-liveness failure.   Stranding is extremely rare.
1188 // We use timers (timed park operations) & periodic polling to detect
1189 // and recover from stranding.  Potentially stranded threads periodically
1190 // wake up and poll the lock.  See the usage of the _Responsible variable.
1191 //
1192 // The CAS() in enter provides for safety and exclusion, while the CAS or
1193 // MEMBAR in exit provides for progress and avoids stranding.  1-0 locking
1194 // eliminates the CAS/MEMBAR from the exit path, but it admits stranding.
1195 // We detect and recover from stranding with timers.
1196 //
1197 // If a thread transiently strands it'll park until (a) another
1198 // thread acquires the lock and then drops the lock, at which time the
1199 // exiting thread will notice and unpark the stranded thread, or, (b)
1200 // the timer expires.  If the lock is high traffic then the stranding latency
1201 // will be low due to (a).  If the lock is low traffic then the odds of
1202 // stranding are lower, although the worst-case stranding latency
1203 // is longer.  Critically, we don't want to put excessive load in the
1204 // platform's timer subsystem.  We want to minimize both the timer injection
1205 // rate (timers created/sec) as well as the number of timers active at
1206 // any one time.  (more precisely, we want to minimize timer-seconds, which is
1207 // the integral of the # of active timers at any instant over time).
1208 // Both impinge on OS scalability.  Given that, at most one thread parked on
1209 // a monitor will use a timer.
1210 //
1211 // There is also the risk of a futile wake-up. If we drop the lock
1212 // another thread can reacquire the lock immediately, and we can
1213 // then wake a thread unnecessarily. This is benign, and we've
1214 // structured the code so the windows are short and the frequency
1215 // of such futile wakups is low.
1216 
1217 void ObjectMonitor::exit(JavaThread* current, bool not_suspended) {
1218   void* cur = owner_raw();
1219   if (current != cur) {
1220     if (LockingMode != LM_LIGHTWEIGHT && current->is_lock_owned((address)cur)) {
1221       assert(_recursions == 0, "invariant");
1222       set_owner_from_BasicLock(cur, current);  // Convert from BasicLock* to Thread*.
1223       _recursions = 0;
1224     } else {
1225       // Apparent unbalanced locking ...
1226       // Naively we'd like to throw IllegalMonitorStateException.
1227       // As a practical matter we can neither allocate nor throw an
1228       // exception as ::exit() can be called from leaf routines.
1229       // see x86_32.ad Fast_Unlock() and the I1 and I2 properties.
1230       // Upon deeper reflection, however, in a properly run JVM the only
1231       // way we should encounter this situation is in the presence of
1232       // unbalanced JNI locking. TODO: CheckJNICalls.
1233       // See also: CR4414101
1234 #ifdef ASSERT
1235       LogStreamHandle(Error, monitorinflation) lsh;
1236       lsh.print_cr("ERROR: ObjectMonitor::exit(): thread=" INTPTR_FORMAT
1237                     " is exiting an ObjectMonitor it does not own.", p2i(current));
1238       lsh.print_cr("The imbalance is possibly caused by JNI locking.");
1239       print_debug_style_on(&lsh);
1240       assert(false, "Non-balanced monitor enter/exit!");
1241 #endif
1242       return;
1243     }
1244   }
1245 
1246   if (_recursions != 0) {
1247     _recursions--;        // this is simple recursive enter
1248     return;
1249   }
1250 
1251   // Invariant: after setting Responsible=null an thread must execute
1252   // a MEMBAR or other serializing instruction before fetching EntryList|cxq.
1253   _Responsible = nullptr;
1254 
1255 #if INCLUDE_JFR
1256   // get the owner's thread id for the MonitorEnter event
1257   // if it is enabled and the thread isn't suspended
1258   if (not_suspended && EventJavaMonitorEnter::is_enabled()) {
1259     _previous_owner_tid = JFR_THREAD_ID(current);
1260   }
1261 #endif
1262 
1263   for (;;) {
1264     assert(current == owner_raw(), "invariant");
1265 
1266     // Drop the lock.
1267     // release semantics: prior loads and stores from within the critical section
1268     // must not float (reorder) past the following store that drops the lock.
1269     // Uses a storeload to separate release_store(owner) from the
1270     // successor check. The try_set_owner() below uses cmpxchg() so
1271     // we get the fence down there.
1272     release_clear_owner(current);
1273     OrderAccess::storeload();
1274 
1275     if ((intptr_t(_EntryList)|intptr_t(_cxq)) == 0 || _succ != nullptr) {
1276       return;
1277     }
1278     // Other threads are blocked trying to acquire the lock.
1279 
1280     // Normally the exiting thread is responsible for ensuring succession,
1281     // but if other successors are ready or other entering threads are spinning
1282     // then this thread can simply store null into _owner and exit without
1283     // waking a successor.  The existence of spinners or ready successors
1284     // guarantees proper succession (liveness).  Responsibility passes to the
1285     // ready or running successors.  The exiting thread delegates the duty.
1286     // More precisely, if a successor already exists this thread is absolved
1287     // of the responsibility of waking (unparking) one.
1288     //
1289     // The _succ variable is critical to reducing futile wakeup frequency.
1290     // _succ identifies the "heir presumptive" thread that has been made
1291     // ready (unparked) but that has not yet run.  We need only one such
1292     // successor thread to guarantee progress.
1293     // See http://www.usenix.org/events/jvm01/full_papers/dice/dice.pdf
1294     // section 3.3 "Futile Wakeup Throttling" for details.
1295     //
1296     // Note that spinners in Enter() also set _succ non-null.
1297     // In the current implementation spinners opportunistically set
1298     // _succ so that exiting threads might avoid waking a successor.
1299     // Another less appealing alternative would be for the exiting thread
1300     // to drop the lock and then spin briefly to see if a spinner managed
1301     // to acquire the lock.  If so, the exiting thread could exit
1302     // immediately without waking a successor, otherwise the exiting
1303     // thread would need to dequeue and wake a successor.
1304     // (Note that we'd need to make the post-drop spin short, but no
1305     // shorter than the worst-case round-trip cache-line migration time.
1306     // The dropped lock needs to become visible to the spinner, and then
1307     // the acquisition of the lock by the spinner must become visible to
1308     // the exiting thread).
1309 
1310     // It appears that an heir-presumptive (successor) must be made ready.
1311     // Only the current lock owner can manipulate the EntryList or
1312     // drain _cxq, so we need to reacquire the lock.  If we fail
1313     // to reacquire the lock the responsibility for ensuring succession
1314     // falls to the new owner.
1315     //
1316     if (try_set_owner_from(nullptr, current) != nullptr) {
1317       return;
1318     }
1319 
1320     guarantee(owner_raw() == current, "invariant");
1321 
1322     ObjectWaiter* w = nullptr;
1323 
1324     w = _EntryList;
1325     if (w != nullptr) {
1326       // I'd like to write: guarantee (w->_thread != current).
1327       // But in practice an exiting thread may find itself on the EntryList.
1328       // Let's say thread T1 calls O.wait().  Wait() enqueues T1 on O's waitset and
1329       // then calls exit().  Exit release the lock by setting O._owner to null.
1330       // Let's say T1 then stalls.  T2 acquires O and calls O.notify().  The
1331       // notify() operation moves T1 from O's waitset to O's EntryList. T2 then
1332       // release the lock "O".  T2 resumes immediately after the ST of null into
1333       // _owner, above.  T2 notices that the EntryList is populated, so it
1334       // reacquires the lock and then finds itself on the EntryList.
1335       // Given all that, we have to tolerate the circumstance where "w" is
1336       // associated with current.
1337       assert(w->TState == ObjectWaiter::TS_ENTER, "invariant");
1338       ExitEpilog(current, w);
1339       return;
1340     }
1341 
1342     // If we find that both _cxq and EntryList are null then just
1343     // re-run the exit protocol from the top.
1344     w = _cxq;
1345     if (w == nullptr) continue;
1346 
1347     // Drain _cxq into EntryList - bulk transfer.
1348     // First, detach _cxq.
1349     // The following loop is tantamount to: w = swap(&cxq, nullptr)
1350     for (;;) {
1351       assert(w != nullptr, "Invariant");
1352       ObjectWaiter* u = Atomic::cmpxchg(&_cxq, w, (ObjectWaiter*)nullptr);
1353       if (u == w) break;
1354       w = u;
1355     }
1356 
1357     assert(w != nullptr, "invariant");
1358     assert(_EntryList == nullptr, "invariant");
1359 
1360     // Convert the LIFO SLL anchored by _cxq into a DLL.
1361     // The list reorganization step operates in O(LENGTH(w)) time.
1362     // It's critical that this step operate quickly as
1363     // "current" still holds the outer-lock, restricting parallelism
1364     // and effectively lengthening the critical section.
1365     // Invariant: s chases t chases u.
1366     // TODO-FIXME: consider changing EntryList from a DLL to a CDLL so
1367     // we have faster access to the tail.
1368 
1369     _EntryList = w;
1370     ObjectWaiter* q = nullptr;
1371     ObjectWaiter* p;
1372     for (p = w; p != nullptr; p = p->_next) {
1373       guarantee(p->TState == ObjectWaiter::TS_CXQ, "Invariant");
1374       p->TState = ObjectWaiter::TS_ENTER;
1375       p->_prev = q;
1376       q = p;
1377     }
1378 
1379     // In 1-0 mode we need: ST EntryList; MEMBAR #storestore; ST _owner = nullptr
1380     // The MEMBAR is satisfied by the release_store() operation in ExitEpilog().
1381 
1382     // See if we can abdicate to a spinner instead of waking a thread.
1383     // A primary goal of the implementation is to reduce the
1384     // context-switch rate.
1385     if (_succ != nullptr) continue;
1386 
1387     w = _EntryList;
1388     if (w != nullptr) {
1389       guarantee(w->TState == ObjectWaiter::TS_ENTER, "invariant");
1390       ExitEpilog(current, w);
1391       return;
1392     }
1393   }
1394 }
1395 
1396 void ObjectMonitor::ExitEpilog(JavaThread* current, ObjectWaiter* Wakee) {
1397   assert(owner_raw() == current, "invariant");
1398 
1399   // Exit protocol:
1400   // 1. ST _succ = wakee
1401   // 2. membar #loadstore|#storestore;
1402   // 2. ST _owner = nullptr
1403   // 3. unpark(wakee)
1404 
1405   _succ = Wakee->_thread;
1406   ParkEvent * Trigger = Wakee->_event;











1407 
1408   // Hygiene -- once we've set _owner = nullptr we can't safely dereference Wakee again.
1409   // The thread associated with Wakee may have grabbed the lock and "Wakee" may be
1410   // out-of-scope (non-extant).
1411   Wakee  = nullptr;
1412 
1413   // Drop the lock.
1414   // Uses a fence to separate release_store(owner) from the LD in unpark().
1415   release_clear_owner(current);
1416   OrderAccess::fence();
1417 
1418   DTRACE_MONITOR_PROBE(contended__exit, this, object(), current);
1419   Trigger->unpark();






1420 
1421   // Maintain stats and report events to JVMTI
1422   OM_PERFDATA_OP(Parks, inc());
1423 }
1424 
1425 // complete_exit exits a lock returning recursion count
1426 // complete_exit requires an inflated monitor
1427 // The _owner field is not always the Thread addr even with an
1428 // inflated monitor, e.g. the monitor can be inflated by a non-owning
1429 // thread due to contention.
1430 intx ObjectMonitor::complete_exit(JavaThread* current) {
1431   assert(InitDone, "Unexpectedly not initialized");
1432 
1433   void* cur = owner_raw();
1434   if (current != cur) {
1435     if (LockingMode != LM_LIGHTWEIGHT && current->is_lock_owned((address)cur)) {
1436       assert(_recursions == 0, "internal state error");
1437       set_owner_from_BasicLock(cur, current);  // Convert from BasicLock* to Thread*.
1438       _recursions = 0;
1439     }
1440   }
1441 
1442   guarantee(current == owner_raw(), "complete_exit not owner");
1443   intx save = _recursions; // record the old recursion count
1444   _recursions = 0;         // set the recursion level to be 0
1445   exit(current);           // exit the monitor
1446   guarantee(owner_raw() != current, "invariant");
1447   return save;
1448 }
1449 
1450 // Checks that the current THREAD owns this monitor and causes an
1451 // immediate return if it doesn't. We don't use the CHECK macro
1452 // because we want the IMSE to be the only exception that is thrown
1453 // from the call site when false is returned. Any other pending
1454 // exception is ignored.
1455 #define CHECK_OWNER()                                                  \
1456   do {                                                                 \
1457     if (!check_owner(THREAD)) {                                        \
1458        assert(HAS_PENDING_EXCEPTION, "expected a pending IMSE here."); \
1459        return;                                                         \
1460      }                                                                 \
1461   } while (false)
1462 
1463 // Returns true if the specified thread owns the ObjectMonitor.
1464 // Otherwise returns false and throws IllegalMonitorStateException
1465 // (IMSE). If there is a pending exception and the specified thread
1466 // is not the owner, that exception will be replaced by the IMSE.
1467 bool ObjectMonitor::check_owner(TRAPS) {
1468   JavaThread* current = THREAD;
1469   void* cur = owner_raw();
1470   assert(cur != anon_owner_ptr(), "no anon owner here");
1471   if (cur == current) {
1472     return true;
1473   }
1474   if (LockingMode != LM_LIGHTWEIGHT && current->is_lock_owned((address)cur)) {
1475     set_owner_from_BasicLock(cur, current);  // Convert from BasicLock* to Thread*.
1476     _recursions = 0;
1477     return true;
1478   }
1479   THROW_MSG_(vmSymbols::java_lang_IllegalMonitorStateException(),
1480              "current thread is not owner", false);
1481 }
1482 
1483 static inline bool is_excluded(const Klass* monitor_klass) {
1484   assert(monitor_klass != nullptr, "invariant");
1485   NOT_JFR_RETURN_(false);
1486   JFR_ONLY(return vmSymbols::jdk_jfr_internal_management_HiddenWait() == monitor_klass->name();)
1487 }
1488 
1489 static void post_monitor_wait_event(EventJavaMonitorWait* event,
1490                                     ObjectMonitor* monitor,
1491                                     uint64_t notifier_tid,
1492                                     jlong timeout,
1493                                     bool timedout) {
1494   assert(event != nullptr, "invariant");
1495   assert(monitor != nullptr, "invariant");
1496   const Klass* monitor_klass = monitor->object()->klass();
1497   if (is_excluded(monitor_klass)) {
1498     return;
1499   }
1500   event->set_monitorClass(monitor_klass);
1501   event->set_timeout(timeout);
1502   // Set an address that is 'unique enough', such that events close in
1503   // time and with the same address are likely (but not guaranteed) to
1504   // belong to the same object.
1505   event->set_address((uintptr_t)monitor);
1506   event->set_notifier(notifier_tid);
1507   event->set_timedOut(timedout);
1508   event->commit();
1509 }
1510 






















1511 // -----------------------------------------------------------------------------
1512 // Wait/Notify/NotifyAll
1513 //
1514 // Note: a subset of changes to ObjectMonitor::wait()
1515 // will need to be replicated in complete_exit
1516 void ObjectMonitor::wait(jlong millis, bool interruptible, TRAPS) {
1517   JavaThread* current = THREAD;
1518 
1519   assert(InitDone, "Unexpectedly not initialized");
1520 
1521   CHECK_OWNER();  // Throws IMSE if not owner.
1522 
1523   EventJavaMonitorWait event;
1524 
1525   // check for a pending interrupt
1526   if (interruptible && current->is_interrupted(true) && !HAS_PENDING_EXCEPTION) {
1527     // post monitor waited event.  Note that this is past-tense, we are done waiting.
1528     if (JvmtiExport::should_post_monitor_waited()) {
1529       // Note: 'false' parameter is passed here because the
1530       // wait was not timed out due to thread interrupt.
1531       JvmtiExport::post_monitor_waited(current, this, false);
1532 
1533       // In this short circuit of the monitor wait protocol, the
1534       // current thread never drops ownership of the monitor and
1535       // never gets added to the wait queue so the current thread
1536       // cannot be made the successor. This means that the
1537       // JVMTI_EVENT_MONITOR_WAITED event handler cannot accidentally
1538       // consume an unpark() meant for the ParkEvent associated with
1539       // this ObjectMonitor.
1540     }
1541     if (event.should_commit()) {
1542       post_monitor_wait_event(&event, this, 0, millis, false);
1543     }
1544     THROW(vmSymbols::java_lang_InterruptedException());
1545     return;
1546   }
1547 
1548   current->set_current_waiting_monitor(this);
1549 




















1550   // create a node to be put into the queue
1551   // Critically, after we reset() the event but prior to park(), we must check
1552   // for a pending interrupt.
1553   ObjectWaiter node(current);
1554   node.TState = ObjectWaiter::TS_WAIT;
1555   current->_ParkEvent->reset();
1556   OrderAccess::fence();          // ST into Event; membar ; LD interrupted-flag
1557 
1558   // Enter the waiting queue, which is a circular doubly linked list in this case
1559   // but it could be a priority queue or any data structure.
1560   // _WaitSetLock protects the wait queue.  Normally the wait queue is accessed only
1561   // by the owner of the monitor *except* in the case where park()
1562   // returns because of a timeout of interrupt.  Contention is exceptionally rare
1563   // so we use a simple spin-lock instead of a heavier-weight blocking lock.
1564 
1565   Thread::SpinAcquire(&_WaitSetLock, "WaitSet - add");
1566   AddWaiter(&node);
1567   Thread::SpinRelease(&_WaitSetLock);
1568 
1569   _Responsible = nullptr;
1570 
1571   intx save = _recursions;     // record the old recursion count
1572   _waiters++;                  // increment the number of waiters
1573   _recursions = 0;             // set the recursion level to be 1
1574   exit(current);               // exit the monitor
1575   guarantee(owner_raw() != current, "invariant");
1576 
1577   // The thread is on the WaitSet list - now park() it.
1578   // On MP systems it's conceivable that a brief spin before we park
1579   // could be profitable.
1580   //
1581   // TODO-FIXME: change the following logic to a loop of the form
1582   //   while (!timeout && !interrupted && _notified == 0) park()
1583 
1584   int ret = OS_OK;
1585   int WasNotified = 0;
1586 
1587   // Need to check interrupt state whilst still _thread_in_vm
1588   bool interrupted = interruptible && current->is_interrupted(false);
1589 
1590   { // State transition wrappers
1591     OSThread* osthread = current->osthread();
1592     OSThreadWaitState osts(osthread, true);
1593 
1594     assert(current->thread_state() == _thread_in_vm, "invariant");
1595 
1596     {
1597       ClearSuccOnSuspend csos(this);
1598       ThreadBlockInVMPreprocess<ClearSuccOnSuspend> tbivs(current, csos, true /* allow_suspend */);
1599       if (interrupted || HAS_PENDING_EXCEPTION) {
1600         // Intentionally empty
1601       } else if (node._notified == 0) {
1602         if (millis <= 0) {
1603           current->_ParkEvent->park();
1604         } else {
1605           ret = current->_ParkEvent->park(millis);
1606         }
1607       }
1608     }
1609 
1610     // Node may be on the WaitSet, the EntryList (or cxq), or in transition
1611     // from the WaitSet to the EntryList.
1612     // See if we need to remove Node from the WaitSet.
1613     // We use double-checked locking to avoid grabbing _WaitSetLock
1614     // if the thread is not on the wait queue.
1615     //
1616     // Note that we don't need a fence before the fetch of TState.
1617     // In the worst case we'll fetch a old-stale value of TS_WAIT previously
1618     // written by the is thread. (perhaps the fetch might even be satisfied
1619     // by a look-aside into the processor's own store buffer, although given
1620     // the length of the code path between the prior ST and this load that's
1621     // highly unlikely).  If the following LD fetches a stale TS_WAIT value
1622     // then we'll acquire the lock and then re-fetch a fresh TState value.
1623     // That is, we fail toward safety.
1624 
1625     if (node.TState == ObjectWaiter::TS_WAIT) {
1626       Thread::SpinAcquire(&_WaitSetLock, "WaitSet - unlink");
1627       if (node.TState == ObjectWaiter::TS_WAIT) {
1628         DequeueSpecificWaiter(&node);       // unlink from WaitSet
1629         assert(node._notified == 0, "invariant");
1630         node.TState = ObjectWaiter::TS_RUN;
1631       }
1632       Thread::SpinRelease(&_WaitSetLock);
1633     }
1634 
1635     // The thread is now either on off-list (TS_RUN),
1636     // on the EntryList (TS_ENTER), or on the cxq (TS_CXQ).
1637     // The Node's TState variable is stable from the perspective of this thread.
1638     // No other threads will asynchronously modify TState.
1639     guarantee(node.TState != ObjectWaiter::TS_WAIT, "invariant");
1640     OrderAccess::loadload();
1641     if (_succ == current) _succ = nullptr;
1642     WasNotified = node._notified;
1643 
1644     // Reentry phase -- reacquire the monitor.
1645     // re-enter contended monitor after object.wait().
1646     // retain OBJECT_WAIT state until re-enter successfully completes
1647     // Thread state is thread_in_vm and oop access is again safe,
1648     // although the raw address of the object may have changed.
1649     // (Don't cache naked oops over safepoints, of course).
1650 
1651     // post monitor waited event. Note that this is past-tense, we are done waiting.
1652     if (JvmtiExport::should_post_monitor_waited()) {
1653       JvmtiExport::post_monitor_waited(current, this, ret == OS_TIMEOUT);
1654 
1655       if (node._notified != 0 && _succ == current) {
1656         // In this part of the monitor wait-notify-reenter protocol it
1657         // is possible (and normal) for another thread to do a fastpath
1658         // monitor enter-exit while this thread is still trying to get
1659         // to the reenter portion of the protocol.
1660         //
1661         // The ObjectMonitor was notified and the current thread is
1662         // the successor which also means that an unpark() has already
1663         // been done. The JVMTI_EVENT_MONITOR_WAITED event handler can
1664         // consume the unpark() that was done when the successor was
1665         // set because the same ParkEvent is shared between Java
1666         // monitors and JVM/TI RawMonitors (for now).
1667         //
1668         // We redo the unpark() to ensure forward progress, i.e., we
1669         // don't want all pending threads hanging (parked) with none
1670         // entering the unlocked monitor.
1671         node._event->unpark();
1672       }
1673     }
1674 
1675     if (event.should_commit()) {
1676       post_monitor_wait_event(&event, this, node._notifier_tid, millis, ret == OS_TIMEOUT);
1677     }
1678 
1679     OrderAccess::fence();
1680 
1681     assert(owner_raw() != current, "invariant");
1682     ObjectWaiter::TStates v = node.TState;
1683     if (v == ObjectWaiter::TS_RUN) {
1684       enter(current);
1685     } else {
1686       guarantee(v == ObjectWaiter::TS_ENTER || v == ObjectWaiter::TS_CXQ, "invariant");
1687       ReenterI(current, &node);
1688       node.wait_reenter_end(this);
1689     }
1690 
1691     // current has reacquired the lock.
1692     // Lifecycle - the node representing current must not appear on any queues.
1693     // Node is about to go out-of-scope, but even if it were immortal we wouldn't
1694     // want residual elements associated with this thread left on any lists.
1695     guarantee(node.TState == ObjectWaiter::TS_RUN, "invariant");
1696     assert(owner_raw() == current, "invariant");
1697     assert(_succ != current, "invariant");
1698   } // OSThreadWaitState()
1699 
1700   current->set_current_waiting_monitor(nullptr);
1701 
1702   guarantee(_recursions == 0, "invariant");
1703   int relock_count = JvmtiDeferredUpdates::get_and_reset_relock_count_after_wait(current);
1704   _recursions =   save          // restore the old recursion count
1705                 + relock_count; //  increased by the deferred relock count
1706   current->inc_held_monitor_count(relock_count); // Deopt never entered these counts.
1707   _waiters--;             // decrement the number of waiters
1708 
1709   // Verify a few postconditions
1710   assert(owner_raw() == current, "invariant");
1711   assert(_succ != current, "invariant");
1712   assert_mark_word_consistency();
1713 
1714   // check if the notification happened
1715   if (!WasNotified) {
1716     // no, it could be timeout or Thread.interrupt() or both
1717     // check for interrupt event, otherwise it is timeout
1718     if (interruptible && current->is_interrupted(true) && !HAS_PENDING_EXCEPTION) {
1719       THROW(vmSymbols::java_lang_InterruptedException());
1720     }
1721   }
1722 
1723   // NOTE: Spurious wake up will be consider as timeout.
1724   // Monitor notify has precedence over thread interrupt.
1725 }
1726 
1727 
1728 // Consider:
1729 // If the lock is cool (cxq == null && succ == null) and we're on an MP system
1730 // then instead of transferring a thread from the WaitSet to the EntryList
1731 // we might just dequeue a thread from the WaitSet and directly unpark() it.
1732 
1733 void ObjectMonitor::INotify(JavaThread* current) {
1734   Thread::SpinAcquire(&_WaitSetLock, "WaitSet - notify");
1735   ObjectWaiter* iterator = DequeueWaiter();
1736   if (iterator != nullptr) {
1737     guarantee(iterator->TState == ObjectWaiter::TS_WAIT, "invariant");
1738     guarantee(iterator->_notified == 0, "invariant");
1739     // Disposition - what might we do with iterator ?
1740     // a.  add it directly to the EntryList - either tail (policy == 1)
1741     //     or head (policy == 0).
1742     // b.  push it onto the front of the _cxq (policy == 2).
1743     // For now we use (b).
1744 
















1745     iterator->TState = ObjectWaiter::TS_ENTER;
1746 
1747     iterator->_notified = 1;
1748     iterator->_notifier_tid = JFR_THREAD_ID(current);
1749 
1750     ObjectWaiter* list = _EntryList;
1751     if (list != nullptr) {
1752       assert(list->_prev == nullptr, "invariant");
1753       assert(list->TState == ObjectWaiter::TS_ENTER, "invariant");
1754       assert(list != iterator, "invariant");
1755     }
1756 
1757     // prepend to cxq
1758     if (list == nullptr) {
1759       iterator->_next = iterator->_prev = nullptr;
1760       _EntryList = iterator;
1761     } else {
1762       iterator->TState = ObjectWaiter::TS_CXQ;
1763       for (;;) {
1764         ObjectWaiter* front = _cxq;
1765         iterator->_next = front;
1766         if (Atomic::cmpxchg(&_cxq, front, iterator) == front) {
1767           break;
1768         }
1769       }
1770     }
1771 
1772     // _WaitSetLock protects the wait queue, not the EntryList.  We could
1773     // move the add-to-EntryList operation, above, outside the critical section
1774     // protected by _WaitSetLock.  In practice that's not useful.  With the
1775     // exception of  wait() timeouts and interrupts the monitor owner
1776     // is the only thread that grabs _WaitSetLock.  There's almost no contention
1777     // on _WaitSetLock so it's not profitable to reduce the length of the
1778     // critical section.
1779 
1780     iterator->wait_reenter_begin(this);

1781   }
1782   Thread::SpinRelease(&_WaitSetLock);
1783 }
1784 
1785 // Consider: a not-uncommon synchronization bug is to use notify() when
1786 // notifyAll() is more appropriate, potentially resulting in stranded
1787 // threads; this is one example of a lost wakeup. A useful diagnostic
1788 // option is to force all notify() operations to behave as notifyAll().
1789 //
1790 // Note: We can also detect many such problems with a "minimum wait".
1791 // When the "minimum wait" is set to a small non-zero timeout value
1792 // and the program does not hang whereas it did absent "minimum wait",
1793 // that suggests a lost wakeup bug.
1794 
1795 void ObjectMonitor::notify(TRAPS) {
1796   JavaThread* current = THREAD;
1797   CHECK_OWNER();  // Throws IMSE if not owner.
1798   if (_WaitSet == nullptr) {
1799     return;
1800   }
1801   DTRACE_MONITOR_PROBE(notify, this, object(), current);
1802   INotify(current);
1803   OM_PERFDATA_OP(Notifications, inc(1));
1804 }
1805 
1806 
1807 // The current implementation of notifyAll() transfers the waiters one-at-a-time
1808 // from the waitset to the EntryList. This could be done more efficiently with a
1809 // single bulk transfer but in practice it's not time-critical. Beware too,
1810 // that in prepend-mode we invert the order of the waiters. Let's say that the
1811 // waitset is "ABCD" and the EntryList is "XYZ". After a notifyAll() in prepend
1812 // mode the waitset will be empty and the EntryList will be "DCBAXYZ".
1813 
1814 void ObjectMonitor::notifyAll(TRAPS) {
1815   JavaThread* current = THREAD;
1816   CHECK_OWNER();  // Throws IMSE if not owner.
1817   if (_WaitSet == nullptr) {
1818     return;
1819   }
1820 
1821   DTRACE_MONITOR_PROBE(notifyAll, this, object(), current);
1822   int tally = 0;
1823   while (_WaitSet != nullptr) {
1824     tally++;
1825     INotify(current);
1826   }
1827 
1828   OM_PERFDATA_OP(Notifications, inc(tally));
1829 }
1830 


























































































1831 // -----------------------------------------------------------------------------
1832 // Adaptive Spinning Support
1833 //
1834 // Adaptive spin-then-block - rational spinning
1835 //
1836 // Note that we spin "globally" on _owner with a classic SMP-polite TATAS
1837 // algorithm.  On high order SMP systems it would be better to start with
1838 // a brief global spin and then revert to spinning locally.  In the spirit of MCS/CLH,
1839 // a contending thread could enqueue itself on the cxq and then spin locally
1840 // on a thread-specific variable such as its ParkEvent._Event flag.
1841 // That's left as an exercise for the reader.  Note that global spinning is
1842 // not problematic on Niagara, as the L2 cache serves the interconnect and
1843 // has both low latency and massive bandwidth.
1844 //
1845 // Broadly, we can fix the spin frequency -- that is, the % of contended lock
1846 // acquisition attempts where we opt to spin --  at 100% and vary the spin count
1847 // (duration) or we can fix the count at approximately the duration of
1848 // a context switch and vary the frequency.   Of course we could also
1849 // vary both satisfying K == Frequency * Duration, where K is adaptive by monitor.
1850 // For a description of 'Adaptive spin-then-block mutual exclusion in
1851 // multi-threaded processing,' see U.S. Pat. No. 8046758.
1852 //
1853 // This implementation varies the duration "D", where D varies with
1854 // the success rate of recent spin attempts. (D is capped at approximately
1855 // length of a round-trip context switch).  The success rate for recent
1856 // spin attempts is a good predictor of the success rate of future spin
1857 // attempts.  The mechanism adapts automatically to varying critical
1858 // section length (lock modality), system load and degree of parallelism.
1859 // D is maintained per-monitor in _SpinDuration and is initialized
1860 // optimistically.  Spin frequency is fixed at 100%.
1861 //
1862 // Note that _SpinDuration is volatile, but we update it without locks
1863 // or atomics.  The code is designed so that _SpinDuration stays within
1864 // a reasonable range even in the presence of races.  The arithmetic
1865 // operations on _SpinDuration are closed over the domain of legal values,
1866 // so at worst a race will install and older but still legal value.
1867 // At the very worst this introduces some apparent non-determinism.
1868 // We might spin when we shouldn't or vice-versa, but since the spin
1869 // count are relatively short, even in the worst case, the effect is harmless.
1870 //
1871 // Care must be taken that a low "D" value does not become an
1872 // an absorbing state.  Transient spinning failures -- when spinning
1873 // is overall profitable -- should not cause the system to converge
1874 // on low "D" values.  We want spinning to be stable and predictable
1875 // and fairly responsive to change and at the same time we don't want
1876 // it to oscillate, become metastable, be "too" non-deterministic,
1877 // or converge on or enter undesirable stable absorbing states.
1878 //
1879 // We implement a feedback-based control system -- using past behavior
1880 // to predict future behavior.  We face two issues: (a) if the
1881 // input signal is random then the spin predictor won't provide optimal
1882 // results, and (b) if the signal frequency is too high then the control
1883 // system, which has some natural response lag, will "chase" the signal.
1884 // (b) can arise from multimodal lock hold times.  Transient preemption
1885 // can also result in apparent bimodal lock hold times.
1886 // Although sub-optimal, neither condition is particularly harmful, as
1887 // in the worst-case we'll spin when we shouldn't or vice-versa.
1888 // The maximum spin duration is rather short so the failure modes aren't bad.
1889 // To be conservative, I've tuned the gain in system to bias toward
1890 // _not spinning.  Relatedly, the system can sometimes enter a mode where it
1891 // "rings" or oscillates between spinning and not spinning.  This happens
1892 // when spinning is just on the cusp of profitability, however, so the
1893 // situation is not dire.  The state is benign -- there's no need to add
1894 // hysteresis control to damp the transition rate between spinning and
1895 // not spinning.
1896 
1897 int ObjectMonitor::Knob_SpinLimit    = 5000;   // derived by an external tool
1898 
1899 static int Knob_Bonus               = 100;     // spin success bonus
1900 static int Knob_Penalty             = 200;     // spin failure penalty
1901 static int Knob_Poverty             = 1000;
1902 static int Knob_FixedSpin           = 0;
1903 static int Knob_PreSpin             = 10;      // 20-100 likely better, but it's not better in my testing.
1904 
1905 inline static int adjust_up(int spin_duration) {
1906   int x = spin_duration;
1907   if (x < ObjectMonitor::Knob_SpinLimit) {
1908     if (x < Knob_Poverty) {
1909       x = Knob_Poverty;
1910     }
1911     return x + Knob_Bonus;
1912   } else {
1913     return spin_duration;
1914   }
1915 }
1916 
1917 inline static int adjust_down(int spin_duration) {
1918   // TODO: Use an AIMD-like policy to adjust _SpinDuration.
1919   // AIMD is globally stable.
1920   int x = spin_duration;
1921   if (x > 0) {
1922     // Consider an AIMD scheme like: x -= (x >> 3) + 100
1923     // This is globally sample and tends to damp the response.
1924     x -= Knob_Penalty;
1925     if (x < 0) { x = 0; }
1926     return x;
1927   } else {
1928     return spin_duration;
1929   }
1930 }
1931 
1932 bool ObjectMonitor::short_fixed_spin(JavaThread* current, int spin_count, bool adapt) {
1933   for (int ctr = 0; ctr < spin_count; ctr++) {
1934     TryLockResult status = TryLock(current);
1935     if (status == TryLockResult::Success) {
1936       if (adapt) {
1937         _SpinDuration = adjust_up(_SpinDuration);
1938       }
1939       return true;
1940     } else if (status == TryLockResult::Interference) {
1941       break;
1942     }
1943     SpinPause();
1944   }
1945   return false;
1946 }
1947 
1948 // Spinning: Fixed frequency (100%), vary duration
1949 bool ObjectMonitor::TrySpin(JavaThread* current) {
1950 
1951   // Dumb, brutal spin.  Good for comparative measurements against adaptive spinning.
1952   int knob_fixed_spin = Knob_FixedSpin;  // 0 (don't spin: default), 2000 good test
1953   if (knob_fixed_spin > 0) {
1954     return short_fixed_spin(current, knob_fixed_spin, false);
1955   }
1956 
1957   // Admission control - verify preconditions for spinning
1958   //
1959   // We always spin a little bit, just to prevent _SpinDuration == 0 from
1960   // becoming an absorbing state.  Put another way, we spin briefly to
1961   // sample, just in case the system load, parallelism, contention, or lock
1962   // modality changed.
1963 
1964   int knob_pre_spin = Knob_PreSpin; // 10 (default), 100, 1000 or 2000
1965   if (short_fixed_spin(current, knob_pre_spin, true)) {
1966     return true;
1967   }
1968 
1969   //
1970   // Consider the following alternative:
1971   // Periodically set _SpinDuration = _SpinLimit and try a long/full
1972   // spin attempt.  "Periodically" might mean after a tally of
1973   // the # of failed spin attempts (or iterations) reaches some threshold.
1974   // This takes us into the realm of 1-out-of-N spinning, where we
1975   // hold the duration constant but vary the frequency.
1976 
1977   int ctr = _SpinDuration;
1978   if (ctr <= 0) return false;
1979 
1980   // We're good to spin ... spin ingress.
1981   // CONSIDER: use Prefetch::write() to avoid RTS->RTO upgrades
1982   // when preparing to LD...CAS _owner, etc and the CAS is likely
1983   // to succeed.
1984   if (_succ == nullptr) {
1985     _succ = current;
1986   }
1987   Thread* prv = nullptr;
1988 
1989   // There are three ways to exit the following loop:
1990   // 1.  A successful spin where this thread has acquired the lock.
1991   // 2.  Spin failure with prejudice
1992   // 3.  Spin failure without prejudice
1993 
1994   while (--ctr >= 0) {
1995 
1996     // Periodic polling -- Check for pending GC
1997     // Threads may spin while they're unsafe.
1998     // We don't want spinning threads to delay the JVM from reaching
1999     // a stop-the-world safepoint or to steal cycles from GC.
2000     // If we detect a pending safepoint we abort in order that
2001     // (a) this thread, if unsafe, doesn't delay the safepoint, and (b)
2002     // this thread, if safe, doesn't steal cycles from GC.
2003     // This is in keeping with the "no loitering in runtime" rule.
2004     // We periodically check to see if there's a safepoint pending.
2005     if ((ctr & 0xFF) == 0) {
2006       // Can't call SafepointMechanism::should_process() since that
2007       // might update the poll values and we could be in a thread_blocked
2008       // state here which is not allowed so just check the poll.
2009       if (SafepointMechanism::local_poll_armed(current)) {
2010         break;
2011       }
2012       SpinPause();
2013     }
2014 
2015     // Probe _owner with TATAS
2016     // If this thread observes the monitor transition or flicker
2017     // from locked to unlocked to locked, then the odds that this
2018     // thread will acquire the lock in this spin attempt go down
2019     // considerably.  The same argument applies if the CAS fails
2020     // or if we observe _owner change from one non-null value to
2021     // another non-null value.   In such cases we might abort
2022     // the spin without prejudice or apply a "penalty" to the
2023     // spin count-down variable "ctr", reducing it by 100, say.
2024 
2025     JavaThread* ox = static_cast<JavaThread*>(owner_raw());
2026     if (ox == nullptr) {
2027       ox = static_cast<JavaThread*>(try_set_owner_from(nullptr, current));
2028       if (ox == nullptr) {
2029         // The CAS succeeded -- this thread acquired ownership
2030         // Take care of some bookkeeping to exit spin state.
2031         if (_succ == current) {
2032           _succ = nullptr;
2033         }
2034 
2035         // Increase _SpinDuration :
2036         // The spin was successful (profitable) so we tend toward
2037         // longer spin attempts in the future.
2038         // CONSIDER: factor "ctr" into the _SpinDuration adjustment.
2039         // If we acquired the lock early in the spin cycle it
2040         // makes sense to increase _SpinDuration proportionally.
2041         // Note that we don't clamp SpinDuration precisely at SpinLimit.
2042         _SpinDuration = adjust_up(_SpinDuration);
2043         return true;
2044       }
2045 
2046       // The CAS failed ... we can take any of the following actions:
2047       // * penalize: ctr -= CASPenalty
2048       // * exit spin with prejudice -- abort without adapting spinner
2049       // * exit spin without prejudice.
2050       // * Since CAS is high-latency, retry again immediately.
2051       break;
2052     }
2053 
2054     // Did lock ownership change hands ?
2055     if (ox != prv && prv != nullptr) {
2056       break;
2057     }
2058     prv = ox;
2059 
2060     if (_succ == nullptr) {
2061       _succ = current;
2062     }
2063   }
2064 
2065   // Spin failed with prejudice -- reduce _SpinDuration.
2066   if (ctr < 0) {
2067     _SpinDuration = adjust_down(_SpinDuration);
2068   }
2069 
2070   if (_succ == current) {
2071     _succ = nullptr;
2072     // Invariant: after setting succ=null a contending thread
2073     // must recheck-retry _owner before parking.  This usually happens
2074     // in the normal usage of TrySpin(), but it's safest
2075     // to make TrySpin() as foolproof as possible.
2076     OrderAccess::fence();
2077     if (TryLock(current) == TryLockResult::Success) {
2078       return true;
2079     }
2080   }
2081 
2082   return false;
2083 }
2084 
2085 
2086 // -----------------------------------------------------------------------------
2087 // WaitSet management ...
2088 
2089 ObjectWaiter::ObjectWaiter(JavaThread* current) {
2090   _next     = nullptr;
2091   _prev     = nullptr;
2092   _notified = 0;

2093   _notifier_tid = 0;

2094   TState    = TS_RUN;
2095   _thread   = current;
2096   _event    = _thread->_ParkEvent;


2097   _active   = false;
2098   assert(_event != nullptr, "invariant");
















2099 }
2100 
2101 void ObjectWaiter::wait_reenter_begin(ObjectMonitor * const mon) {
2102   _active = JavaThreadBlockedOnMonitorEnterState::wait_reenter_begin(_thread, mon);
2103 }
2104 
2105 void ObjectWaiter::wait_reenter_end(ObjectMonitor * const mon) {
2106   JavaThreadBlockedOnMonitorEnterState::wait_reenter_end(_thread, _active);
2107 }
2108 
2109 inline void ObjectMonitor::AddWaiter(ObjectWaiter* node) {
2110   assert(node != nullptr, "should not add null node");
2111   assert(node->_prev == nullptr, "node already in list");
2112   assert(node->_next == nullptr, "node already in list");
2113   // put node at end of queue (circular doubly linked list)
2114   if (_WaitSet == nullptr) {
2115     _WaitSet = node;
2116     node->_prev = node;
2117     node->_next = node;
2118   } else {
2119     ObjectWaiter* head = _WaitSet;
2120     ObjectWaiter* tail = head->_prev;
2121     assert(tail->_next == head, "invariant check");
2122     tail->_next = node;
2123     head->_prev = node;
2124     node->_next = head;
2125     node->_prev = tail;
2126   }
2127 }
2128 
2129 inline ObjectWaiter* ObjectMonitor::DequeueWaiter() {
2130   // dequeue the very first waiter
2131   ObjectWaiter* waiter = _WaitSet;
2132   if (waiter) {
2133     DequeueSpecificWaiter(waiter);
2134   }
2135   return waiter;
2136 }
2137 
2138 inline void ObjectMonitor::DequeueSpecificWaiter(ObjectWaiter* node) {
2139   assert(node != nullptr, "should not dequeue nullptr node");
2140   assert(node->_prev != nullptr, "node already removed from list");
2141   assert(node->_next != nullptr, "node already removed from list");
2142   // when the waiter has woken up because of interrupt,
2143   // timeout or other spurious wake-up, dequeue the
2144   // waiter from waiting list
2145   ObjectWaiter* next = node->_next;
2146   if (next == node) {
2147     assert(node->_prev == node, "invariant check");
2148     _WaitSet = nullptr;
2149   } else {
2150     ObjectWaiter* prev = node->_prev;
2151     assert(prev->_next == node, "invariant check");
2152     assert(next->_prev == node, "invariant check");
2153     next->_prev = prev;
2154     prev->_next = next;
2155     if (_WaitSet == node) {
2156       _WaitSet = next;
2157     }
2158   }
2159   node->_next = nullptr;
2160   node->_prev = nullptr;
2161 }
2162 
2163 // -----------------------------------------------------------------------------
2164 // PerfData support
2165 PerfCounter * ObjectMonitor::_sync_ContendedLockAttempts       = nullptr;
2166 PerfCounter * ObjectMonitor::_sync_FutileWakeups               = nullptr;
2167 PerfCounter * ObjectMonitor::_sync_Parks                       = nullptr;
2168 PerfCounter * ObjectMonitor::_sync_Notifications               = nullptr;
2169 PerfCounter * ObjectMonitor::_sync_Inflations                  = nullptr;
2170 PerfCounter * ObjectMonitor::_sync_Deflations                  = nullptr;
2171 PerfLongVariable * ObjectMonitor::_sync_MonExtant              = nullptr;
2172 
2173 // One-shot global initialization for the sync subsystem.
2174 // We could also defer initialization and initialize on-demand
2175 // the first time we call ObjectSynchronizer::inflate().
2176 // Initialization would be protected - like so many things - by
2177 // the MonitorCache_lock.
2178 
2179 void ObjectMonitor::Initialize() {
2180   assert(!InitDone, "invariant");
2181 
2182   if (!os::is_MP()) {
2183     Knob_SpinLimit = 0;
2184     Knob_PreSpin   = 0;
2185     Knob_FixedSpin = -1;
2186   }
2187 
2188   if (UsePerfData) {
2189     EXCEPTION_MARK;
2190 #define NEWPERFCOUNTER(n)                                                \
2191   {                                                                      \
2192     n = PerfDataManager::create_counter(SUN_RT, #n, PerfData::U_Events,  \
2193                                         CHECK);                          \
2194   }
2195 #define NEWPERFVARIABLE(n)                                                \
2196   {                                                                       \
2197     n = PerfDataManager::create_variable(SUN_RT, #n, PerfData::U_Events,  \
2198                                          CHECK);                          \
2199   }
2200     NEWPERFCOUNTER(_sync_Inflations);
2201     NEWPERFCOUNTER(_sync_Deflations);
2202     NEWPERFCOUNTER(_sync_ContendedLockAttempts);
2203     NEWPERFCOUNTER(_sync_FutileWakeups);
2204     NEWPERFCOUNTER(_sync_Parks);
2205     NEWPERFCOUNTER(_sync_Notifications);
2206     NEWPERFVARIABLE(_sync_MonExtant);
2207 #undef NEWPERFCOUNTER
2208 #undef NEWPERFVARIABLE
2209   }
2210 
2211   _oop_storage = OopStorageSet::create_weak("ObjectSynchronizer Weak", mtSynchronizer);
2212 
2213   DEBUG_ONLY(InitDone = true;)
2214 }
2215 





2216 void ObjectMonitor::print_on(outputStream* st) const {
2217   // The minimal things to print for markWord printing, more can be added for debugging and logging.
2218   st->print("{contentions=0x%08x,waiters=0x%08x"
2219             ",recursions=" INTX_FORMAT ",owner=" INTPTR_FORMAT "}",
2220             contentions(), waiters(), recursions(),
2221             p2i(owner()));
2222 }
2223 void ObjectMonitor::print() const { print_on(tty); }
2224 
2225 #ifdef ASSERT
2226 // Print the ObjectMonitor like a debugger would:
2227 //
2228 // (ObjectMonitor) 0x00007fdfb6012e40 = {
2229 //   _metadata = 0x0000000000000001
2230 //   _object = 0x000000070ff45fd0
2231 //   _pad_buf0 = {
2232 //     [0] = '\0'
2233 //     ...
2234 //     [43] = '\0'
2235 //   }
2236 //   _owner = 0x0000000000000000
2237 //   _previous_owner_tid = 0
2238 //   _pad_buf1 = {
2239 //     [0] = '\0'
2240 //     ...
2241 //     [47] = '\0'
2242 //   }
2243 //   _next_om = 0x0000000000000000
2244 //   _recursions = 0
2245 //   _EntryList = 0x0000000000000000
2246 //   _cxq = 0x0000000000000000
2247 //   _succ = 0x0000000000000000
2248 //   _Responsible = 0x0000000000000000
2249 //   _SpinDuration = 5000
2250 //   _contentions = 0
2251 //   _WaitSet = 0x0000700009756248
2252 //   _waiters = 1
2253 //   _WaitSetLock = 0
2254 // }
2255 //
2256 void ObjectMonitor::print_debug_style_on(outputStream* st) const {
2257   st->print_cr("(ObjectMonitor*) " INTPTR_FORMAT " = {", p2i(this));
2258   st->print_cr("  _metadata = " INTPTR_FORMAT, _metadata);
2259   st->print_cr("  _object = " INTPTR_FORMAT, p2i(object_peek()));
2260   st->print_cr("  _pad_buf0 = {");
2261   st->print_cr("    [0] = '\\0'");
2262   st->print_cr("    ...");
2263   st->print_cr("    [%d] = '\\0'", (int)sizeof(_pad_buf0) - 1);
2264   st->print_cr("  }");
2265   st->print_cr("  _owner = " INTPTR_FORMAT, p2i(owner_raw()));
2266   st->print_cr("  _previous_owner_tid = " UINT64_FORMAT, _previous_owner_tid);
2267   st->print_cr("  _pad_buf1 = {");
2268   st->print_cr("    [0] = '\\0'");
2269   st->print_cr("    ...");
2270   st->print_cr("    [%d] = '\\0'", (int)sizeof(_pad_buf1) - 1);
2271   st->print_cr("  }");
2272   st->print_cr("  _next_om = " INTPTR_FORMAT, p2i(next_om()));
2273   st->print_cr("  _recursions = " INTX_FORMAT, _recursions);
2274   st->print_cr("  _EntryList = " INTPTR_FORMAT, p2i(_EntryList));
2275   st->print_cr("  _cxq = " INTPTR_FORMAT, p2i(_cxq));
2276   st->print_cr("  _succ = " INTPTR_FORMAT, p2i(_succ));
2277   st->print_cr("  _Responsible = " INTPTR_FORMAT, p2i(_Responsible));
2278   st->print_cr("  _SpinDuration = %d", _SpinDuration);
2279   st->print_cr("  _contentions = %d", contentions());
2280   st->print_cr("  _WaitSet = " INTPTR_FORMAT, p2i(_WaitSet));
2281   st->print_cr("  _waiters = %d", _waiters);
2282   st->print_cr("  _WaitSetLock = %d", _WaitSetLock);
2283   st->print_cr("}");
2284 }
2285 #endif
--- EOF ---