1 /*
2 * Copyright (c) 1998, 2026, 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 "classfile/vmSymbols.hpp"
26 #include "gc/shared/collectedHeap.hpp"
27 #include "jfr/jfrEvents.hpp"
28 #include "logging/log.hpp"
29 #include "logging/logStream.hpp"
30 #include "memory/allocation.inline.hpp"
31 #include "memory/padded.hpp"
32 #include "memory/resourceArea.hpp"
33 #include "memory/universe.hpp"
34 #include "oops/markWord.hpp"
35 #include "oops/oop.inline.hpp"
36 #include "runtime/atomicAccess.hpp"
37 #include "runtime/basicLock.inline.hpp"
38 #include "runtime/frame.inline.hpp"
39 #include "runtime/globals.hpp"
40 #include "runtime/handles.inline.hpp"
41 #include "runtime/handshake.hpp"
42 #include "runtime/interfaceSupport.inline.hpp"
43 #include "runtime/javaThread.hpp"
44 #include "runtime/lockStack.inline.hpp"
45 #include "runtime/mutexLocker.hpp"
46 #include "runtime/objectMonitor.inline.hpp"
47 #include "runtime/objectMonitorTable.hpp"
48 #include "runtime/os.inline.hpp"
49 #include "runtime/osThread.hpp"
50 #include "runtime/safepointMechanism.inline.hpp"
51 #include "runtime/safepointVerifiers.hpp"
52 #include "runtime/sharedRuntime.hpp"
53 #include "runtime/stubRoutines.hpp"
54 #include "runtime/synchronizer.hpp"
55 #include "runtime/threads.hpp"
56 #include "runtime/timer.hpp"
57 #include "runtime/timerTrace.hpp"
58 #include "runtime/trimNativeHeap.hpp"
59 #include "runtime/vframe.hpp"
60 #include "runtime/vmThread.hpp"
61 #include "utilities/align.hpp"
62 #include "utilities/concurrentHashTable.inline.hpp"
63 #include "utilities/concurrentHashTableTasks.inline.hpp"
64 #include "utilities/dtrace.hpp"
65 #include "utilities/events.hpp"
66 #include "utilities/globalCounter.inline.hpp"
67 #include "utilities/globalDefinitions.hpp"
68 #include "utilities/linkedlist.hpp"
69 #include "utilities/preserveException.hpp"
70
71 class ObjectMonitorDeflationLogging;
72
73 void MonitorList::add(ObjectMonitor* m) {
74 ObjectMonitor* head;
75 do {
76 head = AtomicAccess::load(&_head);
77 m->set_next_om(head);
78 } while (AtomicAccess::cmpxchg(&_head, head, m) != head);
79
80 size_t count = AtomicAccess::add(&_count, 1u, memory_order_relaxed);
81 size_t old_max;
82 do {
83 old_max = AtomicAccess::load(&_max);
84 if (count <= old_max) {
85 break;
86 }
87 } while (AtomicAccess::cmpxchg(&_max, old_max, count, memory_order_relaxed) != old_max);
88 }
89
90 size_t MonitorList::count() const {
91 return AtomicAccess::load(&_count);
92 }
93
94 size_t MonitorList::max() const {
95 return AtomicAccess::load(&_max);
96 }
97
98 class ObjectMonitorDeflationSafepointer : public StackObj {
99 JavaThread* const _current;
100 ObjectMonitorDeflationLogging* const _log;
101
102 public:
103 ObjectMonitorDeflationSafepointer(JavaThread* current, ObjectMonitorDeflationLogging* log)
104 : _current(current), _log(log) {}
105
106 void block_for_safepoint(const char* op_name, const char* count_name, size_t counter);
107 };
108
109 // Walk the in-use list and unlink deflated ObjectMonitors.
110 // Returns the number of unlinked ObjectMonitors.
111 size_t MonitorList::unlink_deflated(size_t deflated_count,
112 GrowableArray<ObjectMonitor*>* unlinked_list,
113 ObjectMonitorDeflationSafepointer* safepointer) {
114 size_t unlinked_count = 0;
115 ObjectMonitor* prev = nullptr;
116 ObjectMonitor* m = AtomicAccess::load_acquire(&_head);
117
118 while (m != nullptr) {
119 if (m->is_being_async_deflated()) {
120 // Find next live ObjectMonitor. Batch up the unlinkable monitors, so we can
121 // modify the list once per batch. The batch starts at "m".
122 size_t unlinked_batch = 0;
123 ObjectMonitor* next = m;
124 // Look for at most MonitorUnlinkBatch monitors, or the number of
125 // deflated and not unlinked monitors, whatever comes first.
126 assert(deflated_count >= unlinked_count, "Sanity: underflow");
127 size_t unlinked_batch_limit = MIN2<size_t>(deflated_count - unlinked_count, MonitorUnlinkBatch);
128 do {
129 ObjectMonitor* next_next = next->next_om();
130 unlinked_batch++;
131 unlinked_list->append(next);
132 next = next_next;
133 if (unlinked_batch >= unlinked_batch_limit) {
134 // Reached the max batch, so bail out of the gathering loop.
135 break;
136 }
137 if (prev == nullptr && AtomicAccess::load(&_head) != m) {
138 // Current batch used to be at head, but it is not at head anymore.
139 // Bail out and figure out where we currently are. This avoids long
140 // walks searching for new prev during unlink under heavy list inserts.
141 break;
142 }
143 } while (next != nullptr && next->is_being_async_deflated());
144
145 // Unlink the found batch.
146 if (prev == nullptr) {
147 // The current batch is the first batch, so there is a chance that it starts at head.
148 // Optimistically assume no inserts happened, and try to unlink the entire batch from the head.
149 ObjectMonitor* prev_head = AtomicAccess::cmpxchg(&_head, m, next);
150 if (prev_head != m) {
151 // Something must have updated the head. Figure out the actual prev for this batch.
152 for (ObjectMonitor* n = prev_head; n != m; n = n->next_om()) {
153 prev = n;
154 }
155 assert(prev != nullptr, "Should have found the prev for the current batch");
156 prev->set_next_om(next);
157 }
158 } else {
159 // The current batch is preceded by another batch. This guarantees the current batch
160 // does not start at head. Unlink the entire current batch without updating the head.
161 assert(AtomicAccess::load(&_head) != m, "Sanity");
162 prev->set_next_om(next);
163 }
164
165 unlinked_count += unlinked_batch;
166 if (unlinked_count >= deflated_count) {
167 // Reached the max so bail out of the searching loop.
168 // There should be no more deflated monitors left.
169 break;
170 }
171 m = next;
172 } else {
173 prev = m;
174 m = m->next_om();
175 }
176
177 // Must check for a safepoint/handshake and honor it.
178 safepointer->block_for_safepoint("unlinking", "unlinked_count", unlinked_count);
179 }
180
181 #ifdef ASSERT
182 // Invariant: the code above should unlink all deflated monitors.
183 // The code that runs after this unlinking does not expect deflated monitors.
184 // Notably, attempting to deflate the already deflated monitor would break.
185 {
186 ObjectMonitor* m = AtomicAccess::load_acquire(&_head);
187 while (m != nullptr) {
188 assert(!m->is_being_async_deflated(), "All deflated monitors should be unlinked");
189 m = m->next_om();
190 }
191 }
192 #endif
193
194 AtomicAccess::sub(&_count, unlinked_count);
195 return unlinked_count;
196 }
197
198 MonitorList::Iterator MonitorList::iterator() const {
199 return Iterator(AtomicAccess::load_acquire(&_head));
200 }
201
202 ObjectMonitor* MonitorList::Iterator::next() {
203 ObjectMonitor* current = _current;
204 _current = current->next_om();
205 return current;
206 }
207
208 // The "core" versions of monitor enter and exit reside in this file.
209 // The interpreter and compilers contain specialized transliterated
210 // variants of the enter-exit fast-path operations. See c2_MacroAssembler_x86.cpp
211 // fast_lock(...) for instance. If you make changes here, make sure to modify the
212 // interpreter, and both C1 and C2 fast-path inline locking code emission.
213 //
214 // -----------------------------------------------------------------------------
215
216 #ifdef DTRACE_ENABLED
217
218 // Only bother with this argument setup if dtrace is available
219 // TODO-FIXME: probes should not fire when caller is _blocked. assert() accordingly.
220
221 #define DTRACE_MONITOR_PROBE_COMMON(obj, thread) \
222 char* bytes = nullptr; \
223 int len = 0; \
224 jlong jtid = SharedRuntime::get_java_tid(thread); \
225 Symbol* klassname = obj->klass()->name(); \
226 if (klassname != nullptr) { \
227 bytes = (char*)klassname->bytes(); \
228 len = klassname->utf8_length(); \
229 }
230
231 #define DTRACE_MONITOR_WAIT_PROBE(monitor, obj, thread, millis) \
232 { \
233 if (DTraceMonitorProbes) { \
234 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \
235 HOTSPOT_MONITOR_WAIT(jtid, \
236 (uintptr_t)(monitor), bytes, len, (millis)); \
237 } \
238 }
239
240 #define HOTSPOT_MONITOR_PROBE_notify HOTSPOT_MONITOR_NOTIFY
241 #define HOTSPOT_MONITOR_PROBE_notifyAll HOTSPOT_MONITOR_NOTIFYALL
242 #define HOTSPOT_MONITOR_PROBE_waited HOTSPOT_MONITOR_WAITED
243
244 #define DTRACE_MONITOR_PROBE(probe, monitor, obj, thread) \
245 { \
246 if (DTraceMonitorProbes) { \
247 DTRACE_MONITOR_PROBE_COMMON(obj, thread); \
248 HOTSPOT_MONITOR_PROBE_##probe(jtid, /* probe = waited */ \
249 (uintptr_t)(monitor), bytes, len); \
250 } \
251 }
252
253 #else // ndef DTRACE_ENABLED
254
255 #define DTRACE_MONITOR_WAIT_PROBE(obj, thread, millis, mon) {;}
256 #define DTRACE_MONITOR_PROBE(probe, obj, thread, mon) {;}
257
258 #endif // ndef DTRACE_ENABLED
259
260 // This exists only as a workaround of dtrace bug 6254741
261 static int dtrace_waited_probe(ObjectMonitor* monitor, Handle obj, JavaThread* thr) {
262 DTRACE_MONITOR_PROBE(waited, monitor, obj(), thr);
263 return 0;
264 }
265
266 static constexpr size_t inflation_lock_count() {
267 return 256;
268 }
269
270 // Static storage for an array of PlatformMutex.
271 alignas(PlatformMutex) static uint8_t _inflation_locks[inflation_lock_count()][sizeof(PlatformMutex)];
272
273 static inline PlatformMutex* inflation_lock(size_t index) {
274 return reinterpret_cast<PlatformMutex*>(_inflation_locks[index]);
275 }
276
277 void ObjectSynchronizer::initialize() {
278 for (size_t i = 0; i < inflation_lock_count(); i++) {
279 ::new(static_cast<void*>(inflation_lock(i))) PlatformMutex();
280 }
281 // Start the ceiling with the estimate for one thread.
282 set_in_use_list_ceiling(AvgMonitorsPerThreadEstimate);
283
284 // Start the timer for deflations, so it does not trigger immediately.
285 _last_async_deflation_time_ns = os::javaTimeNanos();
286
287 ObjectSynchronizer::create_om_table();
288 }
289
290 MonitorList ObjectSynchronizer::_in_use_list;
291 // monitors_used_above_threshold() policy is as follows:
292 //
293 // The ratio of the current _in_use_list count to the ceiling is used
294 // to determine if we are above MonitorUsedDeflationThreshold and need
295 // to do an async monitor deflation cycle. The ceiling is increased by
296 // AvgMonitorsPerThreadEstimate when a thread is added to the system
297 // and is decreased by AvgMonitorsPerThreadEstimate when a thread is
298 // removed from the system.
299 //
300 // Note: If the _in_use_list max exceeds the ceiling, then
301 // monitors_used_above_threshold() will use the in_use_list max instead
302 // of the thread count derived ceiling because we have used more
303 // ObjectMonitors than the estimated average.
304 //
305 // Note: If deflate_idle_monitors() has NoAsyncDeflationProgressMax
306 // no-progress async monitor deflation cycles in a row, then the ceiling
307 // is adjusted upwards by monitors_used_above_threshold().
308 //
309 // Start the ceiling with the estimate for one thread in initialize()
310 // which is called after cmd line options are processed.
311 static size_t _in_use_list_ceiling = 0;
312 bool volatile ObjectSynchronizer::_is_async_deflation_requested = false;
313 bool volatile ObjectSynchronizer::_is_final_audit = false;
314 jlong ObjectSynchronizer::_last_async_deflation_time_ns = 0;
315 static uintx _no_progress_cnt = 0;
316 static bool _no_progress_skip_increment = false;
317
318 // These checks are required for wait, notify and exit to avoid inflating the monitor to
319 // find out this inline type object cannot be locked.
320 #define CHECK_THROW_NOSYNC_IMSE(obj) \
321 if ((obj)->mark().is_inline_type()) { \
322 /*
323 * A value object can never be synchronized upon. The error message we use
324 * here is (accurate and) consistent with the one we use for identity objects
325 * when the current thread isn't the owner of the monitor.
326 */ \
327 THROW_MSG(vmSymbols::java_lang_IllegalMonitorStateException(), "current thread is not owner"); \
328 }
329
330 #define CHECK_THROW_NOSYNC_IMSE_0(obj) \
331 if ((obj)->mark().is_inline_type()) { \
332 /*
333 * A value object can never be synchronized upon. The error message we use
334 * here is (accurate and) consistent with the one we use for identity objects
335 * when the current thread isn't the owner of the monitor.
336 */ \
337 THROW_MSG_0(vmSymbols::java_lang_IllegalMonitorStateException(), "current thread is not owner"); \
338 }
339
340 // =====================> Quick functions
341
342 // The quick_* forms are special fast-path variants used to improve
343 // performance. In the simplest case, a "quick_*" implementation could
344 // simply return false, in which case the caller will perform the necessary
345 // state transitions and call the slow-path form.
346 // The fast-path is designed to handle frequently arising cases in an efficient
347 // manner and is just a degenerate "optimistic" variant of the slow-path.
348 // returns true -- to indicate the call was satisfied.
349 // returns false -- to indicate the call needs the services of the slow-path.
350 // A no-loitering ordinance is in effect for code in the quick_* family
351 // operators: safepoints or indefinite blocking (blocking that might span a
352 // safepoint) are forbidden. Generally the thread_state() is _in_Java upon
353 // entry.
354 //
355 // Consider: An interesting optimization is to have the JIT recognize the
356 // following common idiom:
357 // synchronized (someobj) { .... ; notify(); }
358 // That is, we find a notify() or notifyAll() call that immediately precedes
359 // the monitorexit operation. In that case the JIT could fuse the operations
360 // into a single notifyAndExit() runtime primitive.
361
362 bool ObjectSynchronizer::quick_notify(oopDesc* obj, JavaThread* current, bool all) {
363 assert(current->thread_state() == _thread_in_Java, "invariant");
364 NoSafepointVerifier nsv;
365 if (obj == nullptr) return false; // slow-path for invalid obj
366 assert(!obj->klass()->is_inline_klass(), "monitor op on inline type");
367 const markWord mark = obj->mark();
368
369 if (mark.is_fast_locked() && current->lock_stack().contains(cast_to_oop(obj))) {
370 // Degenerate notify
371 // fast-locked by caller so by definition the implied waitset is empty.
372 return true;
373 }
374
375 if (mark.has_monitor()) {
376 ObjectMonitor* const mon = read_monitor(obj, mark);
377 if (mon == nullptr) {
378 // Racing with inflation/deflation go slow path
379 return false;
380 }
381 assert(mon->object() == oop(obj), "invariant");
382 if (!mon->has_owner(current)) return false; // slow-path for IMS exception
383
384 if (mon->first_waiter() != nullptr) {
385 // We have one or more waiters. Since this is an inflated monitor
386 // that we own, we quickly notify them here and now, avoiding the slow-path.
387 if (all) {
388 mon->quick_notifyAll(current);
389 } else {
390 mon->quick_notify(current);
391 }
392 }
393 return true;
394 }
395
396 // other IMS exception states take the slow-path
397 return false;
398 }
399
400 // Handle notifications when synchronizing on value based classes
401 void ObjectSynchronizer::handle_sync_on_value_based_class(Handle obj, JavaThread* locking_thread) {
402 assert(locking_thread == Thread::current() || locking_thread->is_obj_deopt_suspend(), "must be");
403 frame last_frame = locking_thread->last_frame();
404 bool bcp_was_adjusted = false;
405 // Don't decrement bcp if it points to the frame's first instruction. This happens when
406 // handle_sync_on_value_based_class() is called because of a synchronized method. There
407 // is no actual monitorenter instruction in the byte code in this case.
408 if (last_frame.is_interpreted_frame() &&
409 (last_frame.interpreter_frame_method()->code_base() < last_frame.interpreter_frame_bcp())) {
410 // adjust bcp to point back to monitorenter so that we print the correct line numbers
411 last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() - 1);
412 bcp_was_adjusted = true;
413 }
414
415 if (DiagnoseSyncOnValueBasedClasses == FATAL_EXIT) {
416 ResourceMark rm;
417 stringStream ss;
418 locking_thread->print_active_stack_on(&ss);
419 char* base = (char*)strstr(ss.base(), "at");
420 char* newline = (char*)strchr(ss.base(), '\n');
421 if (newline != nullptr) {
422 *newline = '\0';
423 }
424 fatal("Synchronizing on object " INTPTR_FORMAT " of klass %s %s", p2i(obj()), obj->klass()->external_name(), base);
425 } else {
426 assert(DiagnoseSyncOnValueBasedClasses == LOG_WARNING, "invalid value for DiagnoseSyncOnValueBasedClasses");
427 ResourceMark rm;
428 Log(valuebasedclasses) vblog;
429
430 vblog.info("Synchronizing on object " INTPTR_FORMAT " of klass %s", p2i(obj()), obj->klass()->external_name());
431 if (locking_thread->has_last_Java_frame()) {
432 LogStream info_stream(vblog.info());
433 locking_thread->print_active_stack_on(&info_stream);
434 } else {
435 vblog.info("Cannot find the last Java frame");
436 }
437
438 EventSyncOnValueBasedClass event;
439 if (event.should_commit()) {
440 event.set_valueBasedClass(obj->klass());
441 event.commit();
442 }
443 }
444
445 if (bcp_was_adjusted) {
446 last_frame.interpreter_frame_set_bcp(last_frame.interpreter_frame_bcp() + 1);
447 }
448 }
449
450 // -----------------------------------------------------------------------------
451 // JNI locks on java objects
452 // NOTE: must use heavy weight monitor to handle jni monitor enter
453 void ObjectSynchronizer::jni_enter(Handle obj, JavaThread* current) {
454 JavaThread* THREAD = current;
455 // Top native frames in the stack will not be seen if we attempt
456 // preemption, since we start walking from the last Java anchor.
457 NoPreemptMark npm(current);
458
459 if (obj->klass()->is_value_based()) {
460 handle_sync_on_value_based_class(obj, current);
461 }
462
463 if (obj->klass()->is_inline_klass()) {
464 ResourceMark rm(THREAD);
465 stringStream ss;
466 ss.print("Cannot synchronize on an instance of value class %s",
467 obj->klass()->external_name());
468 THROW_MSG(vmSymbols::java_lang_IdentityException(), ss.as_string());
469 }
470
471 // the current locking is from JNI instead of Java code
472 current->set_current_pending_monitor_is_from_java(false);
473 // An async deflation can race after the inflate() call and before
474 // enter() can make the ObjectMonitor busy. enter() returns false if
475 // we have lost the race to async deflation and we simply try again.
476 while (true) {
477 BasicLock lock;
478 if (ObjectSynchronizer::inflate_and_enter(obj(), &lock, inflate_cause_jni_enter, current, current) != nullptr) {
479 break;
480 }
481 }
482 current->set_current_pending_monitor_is_from_java(true);
483 }
484
485 // NOTE: must use heavy weight monitor to handle jni monitor exit
486 void ObjectSynchronizer::jni_exit(oop obj, TRAPS) {
487 JavaThread* current = THREAD;
488 CHECK_THROW_NOSYNC_IMSE(obj);
489
490 ObjectMonitor* monitor;
491 monitor = ObjectSynchronizer::inflate_locked_or_imse(obj, inflate_cause_jni_exit, CHECK);
492 // If this thread has locked the object, exit the monitor. We
493 // intentionally do not use CHECK on check_owner because we must exit the
494 // monitor even if an exception was already pending.
495 if (monitor->check_owner(THREAD)) {
496 monitor->exit(current);
497 }
498 }
499
500 // -----------------------------------------------------------------------------
501 // Internal VM locks on java objects
502 // standard constructor, allows locking failures
503 ObjectLocker::ObjectLocker(Handle obj, TRAPS) : _thread(THREAD), _obj(obj),
504 _npm(_thread, _thread->at_preemptable_init() /* ignore_mark */), _skip_exit(false) {
505 assert(!_thread->preempting(), "");
506
507 _thread->check_for_valid_safepoint_state();
508
509 if (_obj() != nullptr) {
510 ObjectSynchronizer::enter(_obj, &_lock, _thread);
511
512 if (_thread->preempting()) {
513 // If preemption was cancelled we acquired the monitor after freezing
514 // the frames. Redoing the vm call laterĀ in thaw will require us to
515 // release it since the call should look like the original one. We
516 // do it in ~ObjectLocker to reduce the window of time we hold the
517 // monitor since we can't do anything useful with it now, and would
518 // otherwise just force other vthreads to preempt in case they try
519 // to acquire this monitor.
520 _skip_exit = !_thread->preemption_cancelled();
521 ObjectSynchronizer::read_monitor(_obj())->set_object_strong();
522 _thread->set_pending_preempted_exception();
523
524 }
525 }
526 }
527
528 ObjectLocker::~ObjectLocker() {
529 if (_obj() != nullptr && !_skip_exit) {
530 ObjectSynchronizer::exit(_obj(), &_lock, _thread);
531 }
532 }
533
534 void ObjectLocker::wait_uninterruptibly(TRAPS) {
535 ObjectSynchronizer::waitUninterruptibly(_obj, 0, _thread);
536 if (_thread->preempting()) {
537 _skip_exit = true;
538 ObjectSynchronizer::read_monitor(_obj())->set_object_strong();
539 _thread->set_pending_preempted_exception();
540 }
541 }
542
543 // -----------------------------------------------------------------------------
544 // Wait/Notify/NotifyAll
545 // NOTE: must use heavy weight monitor to handle wait()
546
547 int ObjectSynchronizer::wait(Handle obj, jlong millis, TRAPS) {
548 JavaThread* current = THREAD;
549 CHECK_THROW_NOSYNC_IMSE_0(obj);
550 if (millis < 0) {
551 THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
552 }
553
554 ObjectMonitor* monitor;
555 monitor = ObjectSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_wait, CHECK_0);
556
557 DTRACE_MONITOR_WAIT_PROBE(monitor, obj(), current, millis);
558 monitor->wait(millis, true, THREAD); // Not CHECK as we need following code
559
560 // This dummy call is in place to get around dtrace bug 6254741. Once
561 // that's fixed we can uncomment the following line, remove the call
562 // and change this function back into a "void" func.
563 // DTRACE_MONITOR_PROBE(waited, monitor, obj(), THREAD);
564 int ret_code = dtrace_waited_probe(monitor, obj, THREAD);
565 return ret_code;
566 }
567
568 void ObjectSynchronizer::waitUninterruptibly(Handle obj, jlong millis, TRAPS) {
569 assert(millis >= 0, "timeout value is negative");
570
571 ObjectMonitor* monitor;
572 monitor = ObjectSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_wait, CHECK);
573 monitor->wait(millis, false, THREAD);
574 }
575
576
577 void ObjectSynchronizer::notify(Handle obj, TRAPS) {
578 JavaThread* current = THREAD;
579 CHECK_THROW_NOSYNC_IMSE(obj);
580
581 markWord mark = obj->mark();
582 if ((mark.is_fast_locked() && current->lock_stack().contains(obj()))) {
583 // Not inflated so there can't be any waiters to notify.
584 return;
585 }
586 ObjectMonitor* monitor = ObjectSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_notify, CHECK);
587 monitor->notify(CHECK);
588 }
589
590 // NOTE: see comment of notify()
591 void ObjectSynchronizer::notifyall(Handle obj, TRAPS) {
592 JavaThread* current = THREAD;
593 CHECK_THROW_NOSYNC_IMSE(obj);
594
595 markWord mark = obj->mark();
596 if ((mark.is_fast_locked() && current->lock_stack().contains(obj()))) {
597 // Not inflated so there can't be any waiters to notify.
598 return;
599 }
600
601 ObjectMonitor* monitor = ObjectSynchronizer::inflate_locked_or_imse(obj(), inflate_cause_notify, CHECK);
602 monitor->notifyAll(CHECK);
603 }
604
605 // -----------------------------------------------------------------------------
606 // Hash Code handling
607
608 struct SharedGlobals {
609 char _pad_prefix[OM_CACHE_LINE_SIZE];
610 // This is a highly shared mostly-read variable.
611 // To avoid false-sharing it needs to be the sole occupant of a cache line.
612 volatile int stw_random;
613 DEFINE_PAD_MINUS_SIZE(1, OM_CACHE_LINE_SIZE, sizeof(volatile int));
614 // Hot RW variable -- Sequester to avoid false-sharing
615 volatile int hc_sequence;
616 DEFINE_PAD_MINUS_SIZE(2, OM_CACHE_LINE_SIZE, sizeof(volatile int));
617 };
618
619 static SharedGlobals GVars;
620
621 // hashCode() generation :
622 //
623 // Possibilities:
624 // * MD5Digest of {obj,stw_random}
625 // * CRC32 of {obj,stw_random} or any linear-feedback shift register function.
626 // * A DES- or AES-style SBox[] mechanism
627 // * One of the Phi-based schemes, such as:
628 // 2654435761 = 2^32 * Phi (golden ratio)
629 // HashCodeValue = ((uintptr_t(obj) >> 3) * 2654435761) ^ GVars.stw_random ;
630 // * A variation of Marsaglia's shift-xor RNG scheme.
631 // * (obj ^ stw_random) is appealing, but can result
632 // in undesirable regularity in the hashCode values of adjacent objects
633 // (objects allocated back-to-back, in particular). This could potentially
634 // result in hashtable collisions and reduced hashtable efficiency.
635 // There are simple ways to "diffuse" the middle address bits over the
636 // generated hashCode values:
637
638 static intptr_t get_next_hash(Thread* current, oop obj) {
639 intptr_t value = 0;
640 if (hashCode == 0) {
641 // This form uses global Park-Miller RNG.
642 // On MP system we'll have lots of RW access to a global, so the
643 // mechanism induces lots of coherency traffic.
644 value = os::random();
645 } else if (hashCode == 1) {
646 // This variation has the property of being stable (idempotent)
647 // between STW operations. This can be useful in some of the 1-0
648 // synchronization schemes.
649 intptr_t addr_bits = cast_from_oop<intptr_t>(obj) >> 3;
650 value = addr_bits ^ (addr_bits >> 5) ^ GVars.stw_random;
651 } else if (hashCode == 2) {
652 value = 1; // for sensitivity testing
653 } else if (hashCode == 3) {
654 value = ++GVars.hc_sequence;
655 } else if (hashCode == 4) {
656 value = cast_from_oop<intptr_t>(obj);
657 } else {
658 // Marsaglia's xor-shift scheme with thread-specific state
659 // This is probably the best overall implementation -- we'll
660 // likely make this the default in future releases.
661 unsigned t = current->_hashStateX;
662 t ^= (t << 11);
663 current->_hashStateX = current->_hashStateY;
664 current->_hashStateY = current->_hashStateZ;
665 current->_hashStateZ = current->_hashStateW;
666 unsigned v = current->_hashStateW;
667 v = (v ^ (v >> 19)) ^ (t ^ (t >> 8));
668 current->_hashStateW = v;
669 value = v;
670 }
671
672 value &= markWord::hash_mask;
673 if (value == 0) value = 0xBAD;
674 assert(value != markWord::no_hash, "invariant");
675 return value;
676 }
677
678 intptr_t ObjectSynchronizer::FastHashCode(Thread* current, oop obj) {
679 // VM should be calling bootstrap method.
680 assert(!obj->klass()->is_inline_klass(), "FastHashCode should not be called for inline classes");
681
682 while (true) {
683 ObjectMonitor* monitor = nullptr;
684 markWord temp, test;
685 intptr_t hash;
686 markWord mark = obj->mark_acquire();
687 // If UseObjectMonitorTable is set the hash can simply be installed in the
688 // object header, since the monitor isn't in the object header.
689 if (UseObjectMonitorTable || !mark.has_monitor()) {
690 hash = mark.hash();
691 if (hash != 0) { // if it has a hash, just return it
692 return hash;
693 }
694 hash = get_next_hash(current, obj); // get a new hash
695 temp = mark.copy_set_hash(hash); // merge the hash into header
696 // try to install the hash
697 test = obj->cas_set_mark(temp, mark);
698 if (test == mark) { // if the hash was installed, return it
699 return hash;
700 }
701 // CAS failed, retry
702 continue;
703
704 // Failed to install the hash. It could be that another thread
705 // installed the hash just before our attempt or inflation has
706 // occurred or... so we fall thru to inflate the monitor for
707 // stability and then install the hash.
708 } else {
709 assert(!mark.is_unlocked() && !mark.is_fast_locked(), "invariant");
710 monitor = mark.monitor();
711 temp = monitor->header();
712 assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
713 hash = temp.hash();
714 if (hash != 0) {
715 // It has a hash.
716
717 // Separate load of dmw/header above from the loads in
718 // is_being_async_deflated().
719
720 // dmw/header and _contentions may get written by different threads.
721 // Make sure to observe them in the same order when having several observers.
722 OrderAccess::loadload_for_IRIW();
723
724 if (monitor->is_being_async_deflated()) {
725 // But we can't safely use the hash if we detect that async
726 // deflation has occurred. So we attempt to restore the
727 // header/dmw to the object's header so that we only retry
728 // once if the deflater thread happens to be slow.
729 monitor->install_displaced_markword_in_object(obj);
730 continue;
731 }
732 return hash;
733 }
734 // Fall thru so we only have one place that installs the hash in
735 // the ObjectMonitor.
736 }
737
738 // NOTE: an async deflation can race after we get the monitor and
739 // before we can update the ObjectMonitor's header with the hash
740 // value below.
741 assert(mark.has_monitor(), "must be");
742 monitor = mark.monitor();
743
744 // Load ObjectMonitor's header/dmw field and see if it has a hash.
745 mark = monitor->header();
746 assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value());
747 hash = mark.hash();
748 if (hash == 0) { // if it does not have a hash
749 hash = get_next_hash(current, obj); // get a new hash
750 temp = mark.copy_set_hash(hash) ; // merge the hash into header
751 assert(temp.is_neutral(), "invariant: header=" INTPTR_FORMAT, temp.value());
752 uintptr_t v = AtomicAccess::cmpxchg(monitor->metadata_addr(), mark.value(), temp.value());
753 test = markWord(v);
754 if (test != mark) {
755 // The attempt to update the ObjectMonitor's header/dmw field
756 // did not work. This can happen if another thread managed to
757 // merge in the hash just before our cmpxchg().
758 // If we add any new usages of the header/dmw field, this code
759 // will need to be updated.
760 hash = test.hash();
761 assert(test.is_neutral(), "invariant: header=" INTPTR_FORMAT, test.value());
762 assert(hash != 0, "should only have lost the race to a thread that set a non-zero hash");
763 }
764 if (monitor->is_being_async_deflated() && !UseObjectMonitorTable) {
765 // If we detect that async deflation has occurred, then we
766 // attempt to restore the header/dmw to the object's header
767 // so that we only retry once if the deflater thread happens
768 // to be slow.
769 monitor->install_displaced_markword_in_object(obj);
770 continue;
771 }
772 }
773 // We finally get the hash.
774 return hash;
775 }
776 }
777
778 bool ObjectSynchronizer::current_thread_holds_lock(JavaThread* current,
779 Handle h_obj) {
780 if (h_obj->mark().is_inline_type()) {
781 return false;
782 }
783 assert(current == JavaThread::current(), "Can only be called on current thread");
784 oop obj = h_obj();
785
786 markWord mark = obj->mark_acquire();
787
788 if (mark.is_fast_locked()) {
789 // fast-locking case, see if lock is in current's lock stack
790 return current->lock_stack().contains(h_obj());
791 }
792
793 while (mark.has_monitor()) {
794 ObjectMonitor* monitor = read_monitor(obj, mark);
795 if (monitor != nullptr) {
796 return monitor->is_entered(current) != 0;
797 }
798 // Racing with inflation/deflation, retry
799 mark = obj->mark_acquire();
800
801 if (mark.is_fast_locked()) {
802 // Some other thread fast_locked, current could not have held the lock
803 return false;
804 }
805 }
806
807 // Unlocked case, header in place
808 assert(mark.is_unlocked(), "sanity check");
809 return false;
810 }
811
812 JavaThread* ObjectSynchronizer::get_lock_owner(ThreadsList * t_list, Handle h_obj) {
813 oop obj = h_obj();
814 markWord mark = obj->mark_acquire();
815
816 if (mark.is_fast_locked()) {
817 // fast-locked so get owner from the object.
818 // owning_thread_from_object() may also return null here:
819 return Threads::owning_thread_from_object(t_list, h_obj());
820 }
821
822 while (mark.has_monitor()) {
823 ObjectMonitor* monitor = read_monitor(obj, mark);
824 if (monitor != nullptr) {
825 return Threads::owning_thread_from_monitor(t_list, monitor);
826 }
827 // Racing with inflation/deflation, retry
828 mark = obj->mark_acquire();
829
830 if (mark.is_fast_locked()) {
831 // Some other thread fast_locked
832 return Threads::owning_thread_from_object(t_list, h_obj());
833 }
834 }
835
836 // Unlocked case, header in place
837 // Cannot have assertion since this object may have been
838 // locked by another thread when reaching here.
839 // assert(mark.is_unlocked(), "sanity check");
840
841 return nullptr;
842 }
843
844 // Visitors ...
845
846 // Iterate over all ObjectMonitors.
847 template <typename Function>
848 void ObjectSynchronizer::monitors_iterate(Function function) {
849 MonitorList::Iterator iter = _in_use_list.iterator();
850 while (iter.has_next()) {
851 ObjectMonitor* monitor = iter.next();
852 function(monitor);
853 }
854 }
855
856 // Iterate ObjectMonitors owned by any thread and where the owner `filter`
857 // returns true.
858 template <typename OwnerFilter>
859 void ObjectSynchronizer::owned_monitors_iterate_filtered(MonitorClosure* closure, OwnerFilter filter) {
860 monitors_iterate([&](ObjectMonitor* monitor) {
861 // This function is only called at a safepoint or when the
862 // target thread is suspended or when the target thread is
863 // operating on itself. The current closures in use today are
864 // only interested in an owned ObjectMonitor and ownership
865 // cannot be dropped under the calling contexts so the
866 // ObjectMonitor cannot be async deflated.
867 if (monitor->has_owner() && filter(monitor)) {
868 assert(!monitor->is_being_async_deflated(), "Owned monitors should not be deflating");
869
870 closure->do_monitor(monitor);
871 }
872 });
873 }
874
875 // Iterate ObjectMonitors where the owner == thread.
876 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure, JavaThread* thread) {
877 int64_t key = ObjectMonitor::owner_id_from(thread);
878 auto thread_filter = [&](ObjectMonitor* monitor) { return monitor->owner() == key; };
879 return owned_monitors_iterate_filtered(closure, thread_filter);
880 }
881
882 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure, oop vthread) {
883 int64_t key = ObjectMonitor::owner_id_from(vthread);
884 auto thread_filter = [&](ObjectMonitor* monitor) { return monitor->owner() == key; };
885 return owned_monitors_iterate_filtered(closure, thread_filter);
886 }
887
888 // Iterate ObjectMonitors owned by any thread.
889 void ObjectSynchronizer::owned_monitors_iterate(MonitorClosure* closure) {
890 auto all_filter = [&](ObjectMonitor* monitor) { return true; };
891 return owned_monitors_iterate_filtered(closure, all_filter);
892 }
893
894 static bool monitors_used_above_threshold(MonitorList* list) {
895 if (MonitorUsedDeflationThreshold == 0) { // disabled case is easy
896 return false;
897 }
898 size_t monitors_used = list->count();
899 if (monitors_used == 0) { // empty list is easy
900 return false;
901 }
902 size_t old_ceiling = ObjectSynchronizer::in_use_list_ceiling();
903 // Make sure that we use a ceiling value that is not lower than
904 // previous, not lower than the recorded max used by the system, and
905 // not lower than the current number of monitors in use (which can
906 // race ahead of max). The result is guaranteed > 0.
907 size_t ceiling = MAX3(old_ceiling, list->max(), monitors_used);
908
909 // Check if our monitor usage is above the threshold:
910 size_t monitor_usage = (monitors_used * 100LL) / ceiling;
911 if (int(monitor_usage) > MonitorUsedDeflationThreshold) {
912 // Deflate monitors if over the threshold percentage, unless no
913 // progress on previous deflations.
914 bool is_above_threshold = true;
915
916 // Check if it's time to adjust the in_use_list_ceiling up, due
917 // to too many async deflation attempts without any progress.
918 if (NoAsyncDeflationProgressMax != 0 &&
919 _no_progress_cnt >= NoAsyncDeflationProgressMax) {
920 double remainder = (100.0 - MonitorUsedDeflationThreshold) / 100.0;
921 size_t delta = (size_t)(ceiling * remainder) + 1;
922 size_t new_ceiling = (ceiling > SIZE_MAX - delta)
923 ? SIZE_MAX // Overflow, let's clamp new_ceiling.
924 : ceiling + delta;
925
926 ObjectSynchronizer::set_in_use_list_ceiling(new_ceiling);
927 log_info(monitorinflation)("Too many deflations without progress; "
928 "bumping in_use_list_ceiling from %zu"
929 " to %zu", old_ceiling, new_ceiling);
930 _no_progress_cnt = 0;
931 ceiling = new_ceiling;
932
933 // Check if our monitor usage is still above the threshold:
934 monitor_usage = (monitors_used * 100LL) / ceiling;
935 is_above_threshold = int(monitor_usage) > MonitorUsedDeflationThreshold;
936 }
937 log_info(monitorinflation)("monitors_used=%zu, ceiling=%zu"
938 ", monitor_usage=%zu, threshold=%d",
939 monitors_used, ceiling, monitor_usage, MonitorUsedDeflationThreshold);
940 return is_above_threshold;
941 }
942
943 return false;
944 }
945
946 size_t ObjectSynchronizer::in_use_list_count() {
947 return _in_use_list.count();
948 }
949
950 size_t ObjectSynchronizer::in_use_list_max() {
951 return _in_use_list.max();
952 }
953
954 size_t ObjectSynchronizer::in_use_list_ceiling() {
955 return _in_use_list_ceiling;
956 }
957
958 void ObjectSynchronizer::dec_in_use_list_ceiling() {
959 AtomicAccess::sub(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate);
960 }
961
962 void ObjectSynchronizer::inc_in_use_list_ceiling() {
963 AtomicAccess::add(&_in_use_list_ceiling, AvgMonitorsPerThreadEstimate);
964 }
965
966 void ObjectSynchronizer::set_in_use_list_ceiling(size_t new_value) {
967 _in_use_list_ceiling = new_value;
968 }
969
970 bool ObjectSynchronizer::is_async_deflation_needed() {
971 if (is_async_deflation_requested()) {
972 // Async deflation request.
973 log_info(monitorinflation)("Async deflation needed: explicit request");
974 return true;
975 }
976
977 jlong time_since_last = time_since_last_async_deflation_ms();
978
979 if (AsyncDeflationInterval > 0 &&
980 time_since_last > AsyncDeflationInterval &&
981 monitors_used_above_threshold(&_in_use_list)) {
982 // It's been longer than our specified deflate interval and there
983 // are too many monitors in use. We don't deflate more frequently
984 // than AsyncDeflationInterval (unless is_async_deflation_requested)
985 // in order to not swamp the MonitorDeflationThread.
986 log_info(monitorinflation)("Async deflation needed: monitors used are above the threshold");
987 return true;
988 }
989
990 if (GuaranteedAsyncDeflationInterval > 0 &&
991 time_since_last > GuaranteedAsyncDeflationInterval) {
992 // It's been longer than our specified guaranteed deflate interval.
993 // We need to clean up the used monitors even if the threshold is
994 // not reached, to keep the memory utilization at bay when many threads
995 // touched many monitors.
996 log_info(monitorinflation)("Async deflation needed: guaranteed interval (%zd ms) "
997 "is greater than time since last deflation (" JLONG_FORMAT " ms)",
998 GuaranteedAsyncDeflationInterval, time_since_last);
999
1000 // If this deflation has no progress, then it should not affect the no-progress
1001 // tracking, otherwise threshold heuristics would think it was triggered, experienced
1002 // no progress, and needs to backoff more aggressively. In this "no progress" case,
1003 // the generic code would bump the no-progress counter, and we compensate for that
1004 // by telling it to skip the update.
1005 //
1006 // If this deflation has progress, then it should let non-progress tracking
1007 // know about this, otherwise the threshold heuristics would kick in, potentially
1008 // experience no-progress due to aggressive cleanup by this deflation, and think
1009 // it is still in no-progress stride. In this "progress" case, the generic code would
1010 // zero the counter, and we allow it to happen.
1011 _no_progress_skip_increment = true;
1012
1013 return true;
1014 }
1015
1016 return false;
1017 }
1018
1019 void ObjectSynchronizer::request_deflate_idle_monitors() {
1020 MonitorLocker ml(MonitorDeflation_lock, Mutex::_no_safepoint_check_flag);
1021 set_is_async_deflation_requested(true);
1022 ml.notify_all();
1023 }
1024
1025 bool ObjectSynchronizer::request_deflate_idle_monitors_from_wb() {
1026 JavaThread* current = JavaThread::current();
1027 bool ret_code = false;
1028
1029 jlong last_time = last_async_deflation_time_ns();
1030
1031 request_deflate_idle_monitors();
1032
1033 const int N_CHECKS = 5;
1034 for (int i = 0; i < N_CHECKS; i++) { // sleep for at most 5 seconds
1035 if (last_async_deflation_time_ns() > last_time) {
1036 log_info(monitorinflation)("Async Deflation happened after %d check(s).", i);
1037 ret_code = true;
1038 break;
1039 }
1040 {
1041 // JavaThread has to honor the blocking protocol.
1042 ThreadBlockInVM tbivm(current);
1043 os::naked_short_sleep(999); // sleep for almost 1 second
1044 }
1045 }
1046 if (!ret_code) {
1047 log_info(monitorinflation)("Async Deflation DID NOT happen after %d checks.", N_CHECKS);
1048 }
1049
1050 return ret_code;
1051 }
1052
1053 jlong ObjectSynchronizer::time_since_last_async_deflation_ms() {
1054 return (os::javaTimeNanos() - last_async_deflation_time_ns()) / (NANOUNITS / MILLIUNITS);
1055 }
1056
1057 // Walk the in-use list and deflate (at most MonitorDeflationMax) idle
1058 // ObjectMonitors. Returns the number of deflated ObjectMonitors.
1059 //
1060 size_t ObjectSynchronizer::deflate_monitor_list(ObjectMonitorDeflationSafepointer* safepointer) {
1061 MonitorList::Iterator iter = _in_use_list.iterator();
1062 size_t deflated_count = 0;
1063 Thread* current = Thread::current();
1064
1065 while (iter.has_next()) {
1066 if (deflated_count >= (size_t)MonitorDeflationMax) {
1067 break;
1068 }
1069 ObjectMonitor* mid = iter.next();
1070 if (mid->deflate_monitor(current)) {
1071 deflated_count++;
1072 }
1073
1074 // Must check for a safepoint/handshake and honor it.
1075 safepointer->block_for_safepoint("deflation", "deflated_count", deflated_count);
1076 }
1077
1078 return deflated_count;
1079 }
1080
1081 class DeflationHandshakeClosure : public HandshakeClosure {
1082 public:
1083 DeflationHandshakeClosure() : HandshakeClosure("DeflationHandshakeClosure") {}
1084
1085 void do_thread(Thread* thread) {
1086 log_trace(monitorinflation)("DeflationHandshakeClosure::do_thread: thread="
1087 INTPTR_FORMAT, p2i(thread));
1088 if (thread->is_Java_thread()) {
1089 // Clear OM cache
1090 JavaThread* jt = JavaThread::cast(thread);
1091 jt->om_clear_monitor_cache();
1092 }
1093 }
1094 };
1095
1096 class VM_RendezvousGCThreads : public VM_Operation {
1097 public:
1098 bool evaluate_at_safepoint() const override { return false; }
1099 VMOp_Type type() const override { return VMOp_RendezvousGCThreads; }
1100 void doit() override {
1101 Universe::heap()->safepoint_synchronize_begin();
1102 Universe::heap()->safepoint_synchronize_end();
1103 };
1104 };
1105
1106 static size_t delete_monitors(GrowableArray<ObjectMonitor*>* delete_list,
1107 ObjectMonitorDeflationSafepointer* safepointer) {
1108 NativeHeapTrimmer::SuspendMark sm("monitor deletion");
1109 size_t deleted_count = 0;
1110 for (ObjectMonitor* monitor: *delete_list) {
1111 delete monitor;
1112 deleted_count++;
1113 // A JavaThread must check for a safepoint/handshake and honor it.
1114 safepointer->block_for_safepoint("deletion", "deleted_count", deleted_count);
1115 }
1116 return deleted_count;
1117 }
1118
1119 class ObjectMonitorDeflationLogging: public StackObj {
1120 LogStreamHandle(Debug, monitorinflation) _debug;
1121 LogStreamHandle(Info, monitorinflation) _info;
1122 LogStream* _stream;
1123 elapsedTimer _timer;
1124
1125 size_t ceiling() const { return ObjectSynchronizer::in_use_list_ceiling(); }
1126 size_t count() const { return ObjectSynchronizer::in_use_list_count(); }
1127 size_t max() const { return ObjectSynchronizer::in_use_list_max(); }
1128
1129 public:
1130 ObjectMonitorDeflationLogging()
1131 : _debug(), _info(), _stream(nullptr) {
1132 if (_debug.is_enabled()) {
1133 _stream = &_debug;
1134 } else if (_info.is_enabled()) {
1135 _stream = &_info;
1136 }
1137 }
1138
1139 void begin() {
1140 if (_stream != nullptr) {
1141 _stream->print_cr("begin deflating: in_use_list stats: ceiling=%zu, count=%zu, max=%zu",
1142 ceiling(), count(), max());
1143 _timer.start();
1144 }
1145 }
1146
1147 void before_handshake(size_t unlinked_count) {
1148 if (_stream != nullptr) {
1149 _timer.stop();
1150 _stream->print_cr("before handshaking: unlinked_count=%zu"
1151 ", in_use_list stats: ceiling=%zu, count="
1152 "%zu, max=%zu",
1153 unlinked_count, ceiling(), count(), max());
1154 }
1155 }
1156
1157 void after_handshake() {
1158 if (_stream != nullptr) {
1159 _stream->print_cr("after handshaking: in_use_list stats: ceiling="
1160 "%zu, count=%zu, max=%zu",
1161 ceiling(), count(), max());
1162 _timer.start();
1163 }
1164 }
1165
1166 void end(size_t deflated_count, size_t unlinked_count) {
1167 if (_stream != nullptr) {
1168 _timer.stop();
1169 if (deflated_count != 0 || unlinked_count != 0 || _debug.is_enabled()) {
1170 _stream->print_cr("deflated_count=%zu, {unlinked,deleted}_count=%zu monitors in %3.7f secs",
1171 deflated_count, unlinked_count, _timer.seconds());
1172 }
1173 _stream->print_cr("end deflating: in_use_list stats: ceiling=%zu, count=%zu, max=%zu",
1174 ceiling(), count(), max());
1175 }
1176 }
1177
1178 void before_block_for_safepoint(const char* op_name, const char* cnt_name, size_t cnt) {
1179 if (_stream != nullptr) {
1180 _timer.stop();
1181 _stream->print_cr("pausing %s: %s=%zu, in_use_list stats: ceiling="
1182 "%zu, count=%zu, max=%zu",
1183 op_name, cnt_name, cnt, ceiling(), count(), max());
1184 }
1185 }
1186
1187 void after_block_for_safepoint(const char* op_name) {
1188 if (_stream != nullptr) {
1189 _stream->print_cr("resuming %s: in_use_list stats: ceiling=%zu"
1190 ", count=%zu, max=%zu", op_name,
1191 ceiling(), count(), max());
1192 _timer.start();
1193 }
1194 }
1195 };
1196
1197 void ObjectMonitorDeflationSafepointer::block_for_safepoint(const char* op_name, const char* count_name, size_t counter) {
1198 if (!SafepointMechanism::should_process(_current)) {
1199 return;
1200 }
1201
1202 // A safepoint/handshake has started.
1203 _log->before_block_for_safepoint(op_name, count_name, counter);
1204
1205 {
1206 // Honor block request.
1207 ThreadBlockInVM tbivm(_current);
1208 }
1209
1210 _log->after_block_for_safepoint(op_name);
1211 }
1212
1213 // This function is called by the MonitorDeflationThread to deflate
1214 // ObjectMonitors.
1215 size_t ObjectSynchronizer::deflate_idle_monitors() {
1216 JavaThread* current = JavaThread::current();
1217 assert(current->is_monitor_deflation_thread(), "The only monitor deflater");
1218
1219 // The async deflation request has been processed.
1220 _last_async_deflation_time_ns = os::javaTimeNanos();
1221 set_is_async_deflation_requested(false);
1222
1223 ObjectMonitorDeflationLogging log;
1224 ObjectMonitorDeflationSafepointer safepointer(current, &log);
1225
1226 log.begin();
1227
1228 // Deflate some idle ObjectMonitors.
1229 size_t deflated_count = deflate_monitor_list(&safepointer);
1230
1231 // Unlink the deflated ObjectMonitors from the in-use list.
1232 size_t unlinked_count = 0;
1233 size_t deleted_count = 0;
1234 if (deflated_count > 0) {
1235 ResourceMark rm(current);
1236 GrowableArray<ObjectMonitor*> delete_list((int)deflated_count);
1237 unlinked_count = _in_use_list.unlink_deflated(deflated_count, &delete_list, &safepointer);
1238
1239 GrowableArray<ObjectMonitorTable::Table*> table_delete_list;
1240 if (UseObjectMonitorTable) {
1241 ObjectMonitorTable::rebuild(&table_delete_list);
1242 }
1243
1244 log.before_handshake(unlinked_count);
1245
1246 // A JavaThread needs to handshake in order to safely free the
1247 // ObjectMonitors that were deflated in this cycle.
1248 DeflationHandshakeClosure dhc;
1249 Handshake::execute(&dhc);
1250 // Also, we sync and desync GC threads around the handshake, so that they can
1251 // safely read the mark-word and look-through to the object-monitor, without
1252 // being afraid that the object-monitor is going away.
1253 VM_RendezvousGCThreads sync_gc;
1254 VMThread::execute(&sync_gc);
1255
1256 log.after_handshake();
1257
1258 // After the handshake, safely free the ObjectMonitors that were
1259 // deflated and unlinked in this cycle.
1260
1261 // Delete the unlinked ObjectMonitors.
1262 deleted_count = delete_monitors(&delete_list, &safepointer);
1263 if (UseObjectMonitorTable) {
1264 ObjectMonitorTable::destroy(&table_delete_list);
1265 }
1266 assert(unlinked_count == deleted_count, "must be");
1267 }
1268
1269 log.end(deflated_count, unlinked_count);
1270
1271 GVars.stw_random = os::random();
1272
1273 if (deflated_count != 0) {
1274 _no_progress_cnt = 0;
1275 } else if (_no_progress_skip_increment) {
1276 _no_progress_skip_increment = false;
1277 } else {
1278 _no_progress_cnt++;
1279 }
1280
1281 return deflated_count;
1282 }
1283
1284 // Monitor cleanup on JavaThread::exit
1285
1286 // Iterate through monitor cache and attempt to release thread's monitors
1287 class ReleaseJavaMonitorsClosure: public MonitorClosure {
1288 private:
1289 JavaThread* _thread;
1290
1291 public:
1292 ReleaseJavaMonitorsClosure(JavaThread* thread) : _thread(thread) {}
1293 void do_monitor(ObjectMonitor* mid) {
1294 mid->complete_exit(_thread);
1295 }
1296 };
1297
1298 // Release all inflated monitors owned by current thread. Lightweight monitors are
1299 // ignored. This is meant to be called during JNI thread detach which assumes
1300 // all remaining monitors are heavyweight. All exceptions are swallowed.
1301 // Scanning the extant monitor list can be time consuming.
1302 // A simple optimization is to add a per-thread flag that indicates a thread
1303 // called jni_monitorenter() during its lifetime.
1304 //
1305 // Instead of NoSafepointVerifier it might be cheaper to
1306 // use an idiom of the form:
1307 // auto int tmp = SafepointSynchronize::_safepoint_counter ;
1308 // <code that must not run at safepoint>
1309 // guarantee (((tmp ^ _safepoint_counter) | (tmp & 1)) == 0) ;
1310 // Since the tests are extremely cheap we could leave them enabled
1311 // for normal product builds.
1312
1313 void ObjectSynchronizer::release_monitors_owned_by_thread(JavaThread* current) {
1314 assert(current == JavaThread::current(), "must be current Java thread");
1315 NoSafepointVerifier nsv;
1316 ReleaseJavaMonitorsClosure rjmc(current);
1317 ObjectSynchronizer::owned_monitors_iterate(&rjmc, current);
1318 assert(!current->has_pending_exception(), "Should not be possible");
1319 current->clear_pending_exception();
1320 }
1321
1322 const char* ObjectSynchronizer::inflate_cause_name(const InflateCause cause) {
1323 switch (cause) {
1324 case inflate_cause_vm_internal: return "VM Internal";
1325 case inflate_cause_monitor_enter: return "Monitor Enter";
1326 case inflate_cause_wait: return "Monitor Wait";
1327 case inflate_cause_notify: return "Monitor Notify";
1328 case inflate_cause_jni_enter: return "JNI Monitor Enter";
1329 case inflate_cause_jni_exit: return "JNI Monitor Exit";
1330 default:
1331 ShouldNotReachHere();
1332 }
1333 return "Unknown";
1334 }
1335
1336 //------------------------------------------------------------------------------
1337 // Debugging code
1338
1339 u_char* ObjectSynchronizer::get_gvars_addr() {
1340 return (u_char*)&GVars;
1341 }
1342
1343 u_char* ObjectSynchronizer::get_gvars_hc_sequence_addr() {
1344 return (u_char*)&GVars.hc_sequence;
1345 }
1346
1347 size_t ObjectSynchronizer::get_gvars_size() {
1348 return sizeof(SharedGlobals);
1349 }
1350
1351 u_char* ObjectSynchronizer::get_gvars_stw_random_addr() {
1352 return (u_char*)&GVars.stw_random;
1353 }
1354
1355 // Do the final audit and print of ObjectMonitor stats; must be done
1356 // by the VMThread at VM exit time.
1357 void ObjectSynchronizer::do_final_audit_and_print_stats() {
1358 assert(Thread::current()->is_VM_thread(), "sanity check");
1359
1360 if (is_final_audit()) { // Only do the audit once.
1361 return;
1362 }
1363 set_is_final_audit();
1364 log_info(monitorinflation)("Starting the final audit.");
1365
1366 if (log_is_enabled(Info, monitorinflation)) {
1367 LogStreamHandle(Info, monitorinflation) ls;
1368 audit_and_print_stats(&ls, true /* on_exit */);
1369 }
1370 }
1371
1372 // This function can be called by the MonitorDeflationThread or it can be called when
1373 // we are trying to exit the VM. The list walker functions can run in parallel with
1374 // the other list operations.
1375 // Calls to this function can be added in various places as a debugging
1376 // aid.
1377 //
1378 void ObjectSynchronizer::audit_and_print_stats(outputStream* ls, bool on_exit) {
1379 int error_cnt = 0;
1380
1381 ls->print_cr("Checking in_use_list:");
1382 chk_in_use_list(ls, &error_cnt);
1383
1384 if (error_cnt == 0) {
1385 ls->print_cr("No errors found in in_use_list checks.");
1386 } else {
1387 log_error(monitorinflation)("found in_use_list errors: error_cnt=%d", error_cnt);
1388 }
1389
1390 // When exiting, only log the interesting entries at the Info level.
1391 // When called at intervals by the MonitorDeflationThread, log output
1392 // at the Trace level since there can be a lot of it.
1393 if (!on_exit && log_is_enabled(Trace, monitorinflation)) {
1394 LogStreamHandle(Trace, monitorinflation) ls_tr;
1395 log_in_use_monitor_details(&ls_tr, true /* log_all */);
1396 } else if (on_exit) {
1397 log_in_use_monitor_details(ls, false /* log_all */);
1398 }
1399
1400 ls->flush();
1401
1402 guarantee(error_cnt == 0, "ERROR: found monitor list errors: error_cnt=%d", error_cnt);
1403 }
1404
1405 // Check the in_use_list; log the results of the checks.
1406 void ObjectSynchronizer::chk_in_use_list(outputStream* out, int *error_cnt_p) {
1407 size_t l_in_use_count = _in_use_list.count();
1408 size_t l_in_use_max = _in_use_list.max();
1409 out->print_cr("count=%zu, max=%zu", l_in_use_count,
1410 l_in_use_max);
1411
1412 size_t ck_in_use_count = 0;
1413 MonitorList::Iterator iter = _in_use_list.iterator();
1414 while (iter.has_next()) {
1415 ObjectMonitor* mid = iter.next();
1416 chk_in_use_entry(mid, out, error_cnt_p);
1417 ck_in_use_count++;
1418 }
1419
1420 if (l_in_use_count == ck_in_use_count) {
1421 out->print_cr("in_use_count=%zu equals ck_in_use_count=%zu",
1422 l_in_use_count, ck_in_use_count);
1423 } else {
1424 out->print_cr("WARNING: in_use_count=%zu is not equal to "
1425 "ck_in_use_count=%zu", l_in_use_count,
1426 ck_in_use_count);
1427 }
1428
1429 size_t ck_in_use_max = _in_use_list.max();
1430 if (l_in_use_max == ck_in_use_max) {
1431 out->print_cr("in_use_max=%zu equals ck_in_use_max=%zu",
1432 l_in_use_max, ck_in_use_max);
1433 } else {
1434 out->print_cr("WARNING: in_use_max=%zu is not equal to "
1435 "ck_in_use_max=%zu", l_in_use_max, ck_in_use_max);
1436 }
1437 }
1438
1439 // Check an in-use monitor entry; log any errors.
1440 void ObjectSynchronizer::chk_in_use_entry(ObjectMonitor* n, outputStream* out,
1441 int* error_cnt_p) {
1442 if (n->owner_is_DEFLATER_MARKER()) {
1443 // This could happen when monitor deflation blocks for a safepoint.
1444 return;
1445 }
1446
1447
1448 if (n->metadata() == 0) {
1449 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor must "
1450 "have non-null _metadata (header/hash) field.", p2i(n));
1451 *error_cnt_p = *error_cnt_p + 1;
1452 }
1453
1454 const oop obj = n->object_peek();
1455 if (obj == nullptr) {
1456 return;
1457 }
1458
1459 const markWord mark = obj->mark();
1460 // Note: When using ObjectMonitorTable we may observe an intermediate state,
1461 // where the monitor is globally visible, but no thread has yet transitioned
1462 // the markWord. To avoid reporting a false positive during this transition, we
1463 // skip the `!mark.has_monitor()` test if we are using the ObjectMonitorTable.
1464 if (!UseObjectMonitorTable && !mark.has_monitor()) {
1465 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's "
1466 "object does not think it has a monitor: obj="
1467 INTPTR_FORMAT ", mark=" INTPTR_FORMAT, p2i(n),
1468 p2i(obj), mark.value());
1469 *error_cnt_p = *error_cnt_p + 1;
1470 return;
1471 }
1472
1473 ObjectMonitor* const obj_mon = read_monitor(obj, mark);
1474 if (n != obj_mon) {
1475 out->print_cr("ERROR: monitor=" INTPTR_FORMAT ": in-use monitor's "
1476 "object does not refer to the same monitor: obj="
1477 INTPTR_FORMAT ", mark=" INTPTR_FORMAT ", obj_mon="
1478 INTPTR_FORMAT, p2i(n), p2i(obj), mark.value(), p2i(obj_mon));
1479 *error_cnt_p = *error_cnt_p + 1;
1480 }
1481 }
1482
1483 // Log details about ObjectMonitors on the in_use_list. The 'BHL'
1484 // flags indicate why the entry is in-use, 'object' and 'object type'
1485 // indicate the associated object and its type.
1486 void ObjectSynchronizer::log_in_use_monitor_details(outputStream* out, bool log_all) {
1487 if (_in_use_list.count() > 0) {
1488 stringStream ss;
1489 out->print_cr("In-use monitor info%s:", log_all ? "" : " (eliding idle monitors)");
1490 out->print_cr("(B -> is_busy, H -> has hash code, L -> lock status)");
1491 out->print_cr("%18s %s %18s %18s",
1492 "monitor", "BHL", "object", "object type");
1493 out->print_cr("================== === ================== ==================");
1494
1495 auto is_interesting = [&](ObjectMonitor* monitor) {
1496 return log_all || monitor->has_owner() || monitor->is_busy();
1497 };
1498
1499 monitors_iterate([&](ObjectMonitor* monitor) {
1500 if (is_interesting(monitor)) {
1501 const oop obj = monitor->object_peek();
1502 const intptr_t hash = UseObjectMonitorTable ? monitor->hash() : monitor->header().hash();
1503 ResourceMark rm;
1504 out->print(INTPTR_FORMAT " %d%d%d " INTPTR_FORMAT " %s", p2i(monitor),
1505 monitor->is_busy(), hash != 0, monitor->has_owner(),
1506 p2i(obj), obj == nullptr ? "" : obj->klass()->external_name());
1507 if (monitor->is_busy()) {
1508 out->print(" (%s)", monitor->is_busy_to_string(&ss));
1509 ss.reset();
1510 }
1511 out->cr();
1512 }
1513 });
1514 }
1515
1516 out->flush();
1517 }
1518
1519 ObjectMonitor* ObjectSynchronizer::get_or_insert_monitor_from_table(oop object, bool* inserted) {
1520 ObjectMonitor* monitor = get_monitor_from_table(object);
1521 if (monitor != nullptr) {
1522 *inserted = false;
1523 return monitor;
1524 }
1525
1526 ObjectMonitor* alloced_monitor = new ObjectMonitor(object);
1527 alloced_monitor->set_anonymous_owner();
1528
1529 // Try insert monitor
1530 monitor = add_monitor(alloced_monitor, object);
1531
1532 *inserted = alloced_monitor == monitor;
1533 if (!*inserted) {
1534 delete alloced_monitor;
1535 }
1536
1537 return monitor;
1538 }
1539
1540 static void log_inflate(Thread* current, oop object, ObjectSynchronizer::InflateCause cause) {
1541 if (log_is_enabled(Trace, monitorinflation)) {
1542 ResourceMark rm(current);
1543 log_trace(monitorinflation)("inflate: object=" INTPTR_FORMAT ", mark="
1544 INTPTR_FORMAT ", type='%s' cause=%s", p2i(object),
1545 object->mark().value(), object->klass()->external_name(),
1546 ObjectSynchronizer::inflate_cause_name(cause));
1547 }
1548 }
1549
1550 static void post_monitor_inflate_event(EventJavaMonitorInflate* event,
1551 const oop obj,
1552 ObjectSynchronizer::InflateCause cause) {
1553 assert(event != nullptr, "invariant");
1554 const Klass* monitor_klass = obj->klass();
1555 if (ObjectMonitor::is_jfr_excluded(monitor_klass)) {
1556 return;
1557 }
1558 event->set_monitorClass(monitor_klass);
1559 event->set_address((uintptr_t)(void*)obj);
1560 event->set_cause((u1)cause);
1561 event->commit();
1562 }
1563
1564 ObjectMonitor* ObjectSynchronizer::get_or_insert_monitor(oop object, JavaThread* current, ObjectSynchronizer::InflateCause cause) {
1565 assert(UseObjectMonitorTable, "must be");
1566
1567 EventJavaMonitorInflate event;
1568
1569 bool inserted;
1570 ObjectMonitor* monitor = get_or_insert_monitor_from_table(object, &inserted);
1571
1572 if (inserted) {
1573 log_inflate(current, object, cause);
1574 if (event.should_commit()) {
1575 post_monitor_inflate_event(&event, object, cause);
1576 }
1577
1578 // The monitor has an anonymous owner so it is safe from async deflation.
1579 ObjectSynchronizer::_in_use_list.add(monitor);
1580 }
1581
1582 return monitor;
1583 }
1584
1585 // Add the hashcode to the monitor to match the object and put it in the hashtable.
1586 ObjectMonitor* ObjectSynchronizer::add_monitor(ObjectMonitor* monitor, oop obj) {
1587 assert(UseObjectMonitorTable, "must be");
1588 assert(obj == monitor->object(), "must be");
1589
1590 intptr_t hash = obj->mark().hash();
1591 assert(hash != 0, "must be set when claiming the object monitor");
1592 monitor->set_hash(hash);
1593
1594 return ObjectMonitorTable::monitor_put_get(monitor, obj);
1595 }
1596
1597 void ObjectSynchronizer::remove_monitor(ObjectMonitor* monitor, oop obj) {
1598 assert(UseObjectMonitorTable, "must be");
1599 assert(monitor->object_peek() == obj, "must be, cleared objects are removed by is_dead");
1600
1601 ObjectMonitorTable::remove_monitor_entry(monitor);
1602 }
1603
1604 void ObjectSynchronizer::deflate_mark_word(oop obj) {
1605 assert(UseObjectMonitorTable, "must be");
1606
1607 markWord mark = obj->mark_acquire();
1608 assert(!mark.has_no_hash(), "obj with inflated monitor must have had a hash");
1609
1610 while (mark.has_monitor()) {
1611 const markWord new_mark = mark.clear_lock_bits().set_unlocked();
1612 mark = obj->cas_set_mark(new_mark, mark);
1613 }
1614 }
1615
1616 void ObjectSynchronizer::create_om_table() {
1617 if (!UseObjectMonitorTable) {
1618 return;
1619 }
1620 ObjectMonitorTable::create();
1621 }
1622
1623 class ObjectSynchronizer::LockStackInflateContendedLocks : private OopClosure {
1624 private:
1625 oop _contended_oops[LockStack::CAPACITY];
1626 int _length;
1627
1628 void do_oop(oop* o) final {
1629 oop obj = *o;
1630 if (obj->mark_acquire().has_monitor()) {
1631 if (_length > 0 && _contended_oops[_length - 1] == obj) {
1632 // Recursive
1633 return;
1634 }
1635 _contended_oops[_length++] = obj;
1636 }
1637 }
1638
1639 void do_oop(narrowOop* o) final {
1640 ShouldNotReachHere();
1641 }
1642
1643 public:
1644 LockStackInflateContendedLocks() :
1645 _contended_oops(),
1646 _length(0) {};
1647
1648 void inflate(JavaThread* current) {
1649 assert(current == JavaThread::current(), "must be");
1650 current->lock_stack().oops_do(this);
1651 for (int i = 0; i < _length; i++) {
1652 ObjectSynchronizer::
1653 inflate_fast_locked_object(_contended_oops[i], ObjectSynchronizer::inflate_cause_vm_internal, current, current);
1654 }
1655 }
1656 };
1657
1658 void ObjectSynchronizer::ensure_lock_stack_space(JavaThread* current) {
1659 assert(current == JavaThread::current(), "must be");
1660 LockStack& lock_stack = current->lock_stack();
1661
1662 // Make room on lock_stack
1663 if (lock_stack.is_full()) {
1664 // Inflate contended objects
1665 LockStackInflateContendedLocks().inflate(current);
1666 if (lock_stack.is_full()) {
1667 // Inflate the oldest object
1668 inflate_fast_locked_object(lock_stack.bottom(), ObjectSynchronizer::inflate_cause_vm_internal, current, current);
1669 }
1670 }
1671 }
1672
1673 class ObjectSynchronizer::CacheSetter : StackObj {
1674 JavaThread* const _thread;
1675 BasicLock* const _lock;
1676 ObjectMonitor* _monitor;
1677
1678 NONCOPYABLE(CacheSetter);
1679
1680 public:
1681 CacheSetter(JavaThread* thread, BasicLock* lock) :
1682 _thread(thread),
1683 _lock(lock),
1684 _monitor(nullptr) {}
1685
1686 ~CacheSetter() {
1687 // Only use the cache if using the table.
1688 if (UseObjectMonitorTable) {
1689 if (_monitor != nullptr) {
1690 // If the monitor is already in the BasicLock cache then it is most
1691 // likely in the thread cache, do not set it again to avoid reordering.
1692 if (_monitor != _lock->object_monitor_cache()) {
1693 _thread->om_set_monitor_cache(_monitor);
1694 _lock->set_object_monitor_cache(_monitor);
1695 }
1696 } else {
1697 _lock->clear_object_monitor_cache();
1698 }
1699 }
1700 }
1701
1702 void set_monitor(ObjectMonitor* monitor) {
1703 assert(_monitor == nullptr, "only set once");
1704 _monitor = monitor;
1705 }
1706
1707 };
1708
1709 // Reads first from the BasicLock cache then from the OMCache in the current thread.
1710 // C2 fast-path may have put the monitor in the cache in the BasicLock.
1711 inline static ObjectMonitor* read_caches(JavaThread* current, BasicLock* lock, oop object) {
1712 ObjectMonitor* monitor = lock->object_monitor_cache();
1713 if (monitor == nullptr) {
1714 monitor = current->om_get_from_monitor_cache(object);
1715 }
1716 return monitor;
1717 }
1718
1719 class ObjectSynchronizer::VerifyThreadState {
1720 bool _no_safepoint;
1721
1722 public:
1723 VerifyThreadState(JavaThread* locking_thread, JavaThread* current) : _no_safepoint(locking_thread != current) {
1724 assert(current == Thread::current(), "must be");
1725 assert(locking_thread == current || locking_thread->is_obj_deopt_suspend(), "locking_thread may not run concurrently");
1726 if (_no_safepoint) {
1727 DEBUG_ONLY(JavaThread::current()->inc_no_safepoint_count();)
1728 }
1729 }
1730 ~VerifyThreadState() {
1731 if (_no_safepoint){
1732 DEBUG_ONLY(JavaThread::current()->dec_no_safepoint_count();)
1733 }
1734 }
1735 };
1736
1737 inline bool ObjectSynchronizer::fast_lock_try_enter(oop obj, LockStack& lock_stack, JavaThread* current) {
1738 markWord mark = obj->mark();
1739 while (mark.is_unlocked()) {
1740 ensure_lock_stack_space(current);
1741 assert(!lock_stack.is_full(), "must have made room on the lock stack");
1742 assert(!lock_stack.contains(obj), "thread must not already hold the lock");
1743 // Try to swing into 'fast-locked' state.
1744 markWord locked_mark = mark.set_fast_locked();
1745 markWord old_mark = mark;
1746 mark = obj->cas_set_mark(locked_mark, old_mark);
1747 if (old_mark == mark) {
1748 // Successfully fast-locked, push object to lock-stack and return.
1749 lock_stack.push(obj);
1750 return true;
1751 }
1752 }
1753 return false;
1754 }
1755
1756 bool ObjectSynchronizer::fast_lock_spin_enter(oop obj, LockStack& lock_stack, JavaThread* current, bool observed_deflation) {
1757 assert(UseObjectMonitorTable, "must be");
1758 // Will spin with exponential backoff with an accumulative O(2^spin_limit) spins.
1759 const int log_spin_limit = os::is_MP() ? FastLockingSpins : 1;
1760 const int log_min_safepoint_check_interval = 10;
1761
1762 markWord mark = obj->mark();
1763 const auto should_spin = [&]() {
1764 if (!mark.has_monitor()) {
1765 // Spin while not inflated.
1766 return true;
1767 } else if (observed_deflation) {
1768 // Spin while monitor is being deflated.
1769 ObjectMonitor* monitor = ObjectSynchronizer::read_monitor(obj, mark);
1770 return monitor == nullptr || monitor->is_being_async_deflated();
1771 }
1772 // Else stop spinning.
1773 return false;
1774 };
1775 // Always attempt to lock once even when safepoint synchronizing.
1776 bool should_process = false;
1777 for (int i = 0; should_spin() && !should_process && i < log_spin_limit; i++) {
1778 // Spin with exponential backoff.
1779 const int total_spin_count = 1 << i;
1780 const int inner_spin_count = MIN2(1 << log_min_safepoint_check_interval, total_spin_count);
1781 const int outer_spin_count = total_spin_count / inner_spin_count;
1782 for (int outer = 0; outer < outer_spin_count; outer++) {
1783 should_process = SafepointMechanism::should_process(current);
1784 if (should_process) {
1785 // Stop spinning for safepoint.
1786 break;
1787 }
1788 for (int inner = 1; inner < inner_spin_count; inner++) {
1789 SpinPause();
1790 }
1791 }
1792
1793 if (fast_lock_try_enter(obj, lock_stack, current)) return true;
1794 }
1795 return false;
1796 }
1797
1798 void ObjectSynchronizer::enter_for(Handle obj, BasicLock* lock, JavaThread* locking_thread) {
1799 // When called with locking_thread != Thread::current() some mechanism must synchronize
1800 // the locking_thread with respect to the current thread. Currently only used when
1801 // deoptimizing and re-locking locks. See Deoptimization::relock_objects
1802 assert(locking_thread == Thread::current() || locking_thread->is_obj_deopt_suspend(), "must be");
1803
1804 assert(!UseObjectMonitorTable || lock->object_monitor_cache() == nullptr, "must be cleared");
1805 JavaThread* current = JavaThread::current();
1806 VerifyThreadState vts(locking_thread, current);
1807
1808 if (obj->klass()->is_value_based()) {
1809 ObjectSynchronizer::handle_sync_on_value_based_class(obj, locking_thread);
1810 }
1811
1812 LockStack& lock_stack = locking_thread->lock_stack();
1813
1814 ObjectMonitor* monitor = nullptr;
1815 if (lock_stack.contains(obj())) {
1816 monitor = inflate_fast_locked_object(obj(), ObjectSynchronizer::inflate_cause_monitor_enter, locking_thread, current);
1817 bool entered = monitor->enter_for(locking_thread);
1818 assert(entered, "recursive ObjectMonitor::enter_for must succeed");
1819 } else {
1820 do {
1821 // It is assumed that enter_for must enter on an object without contention.
1822 monitor = inflate_and_enter(obj(), lock, ObjectSynchronizer::inflate_cause_monitor_enter, locking_thread, current);
1823 // But there may still be a race with deflation.
1824 } while (monitor == nullptr);
1825 }
1826
1827 assert(monitor != nullptr, "ObjectSynchronizer::enter_for must succeed");
1828 assert(!UseObjectMonitorTable || lock->object_monitor_cache() == nullptr, "unused. already cleared");
1829 }
1830
1831 void ObjectSynchronizer::enter(Handle obj, BasicLock* lock, JavaThread* current) {
1832 assert(current == JavaThread::current(), "must be");
1833
1834 if (obj->klass()->is_value_based()) {
1835 ObjectSynchronizer::handle_sync_on_value_based_class(obj, current);
1836 }
1837
1838 CacheSetter cache_setter(current, lock);
1839
1840 // Used when deflation is observed. Progress here requires progress
1841 // from the deflator. After observing that the deflator is not
1842 // making progress (after two yields), switch to sleeping.
1843 SpinYield spin_yield(0, 2);
1844 bool observed_deflation = false;
1845
1846 LockStack& lock_stack = current->lock_stack();
1847
1848 if (!lock_stack.is_full() && lock_stack.try_recursive_enter(obj())) {
1849 // Recursively fast locked
1850 return;
1851 }
1852
1853 if (lock_stack.contains(obj())) {
1854 ObjectMonitor* monitor = inflate_fast_locked_object(obj(), ObjectSynchronizer::inflate_cause_monitor_enter, current, current);
1855 bool entered = monitor->enter(current);
1856 assert(entered, "recursive ObjectMonitor::enter must succeed");
1857 cache_setter.set_monitor(monitor);
1858 return;
1859 }
1860
1861 while (true) {
1862 // Fast-locking does not use the 'lock' argument.
1863 // Fast-lock spinning to avoid inflating for short critical sections.
1864 // The goal is to only inflate when the extra cost of using ObjectMonitors
1865 // is worth it.
1866 // If deflation has been observed we also spin while deflation is ongoing.
1867 if (fast_lock_try_enter(obj(), lock_stack, current)) {
1868 return;
1869 } else if (UseObjectMonitorTable && fast_lock_spin_enter(obj(), lock_stack, current, observed_deflation)) {
1870 return;
1871 }
1872
1873 if (observed_deflation) {
1874 spin_yield.wait();
1875 }
1876
1877 ObjectMonitor* monitor = inflate_and_enter(obj(), lock, ObjectSynchronizer::inflate_cause_monitor_enter, current, current);
1878 if (monitor != nullptr) {
1879 cache_setter.set_monitor(monitor);
1880 return;
1881 }
1882
1883 // If inflate_and_enter returns nullptr it is because a deflated monitor
1884 // was encountered. Fallback to fast locking. The deflater is responsible
1885 // for clearing out the monitor and transitioning the markWord back to
1886 // fast locking.
1887 observed_deflation = true;
1888 }
1889 }
1890
1891 void ObjectSynchronizer::exit(oop object, BasicLock* lock, JavaThread* current) {
1892 assert(current == Thread::current(), "must be");
1893
1894 markWord mark = object->mark();
1895 assert(!mark.is_unlocked(), "must be");
1896
1897 LockStack& lock_stack = current->lock_stack();
1898 if (mark.is_fast_locked()) {
1899 if (lock_stack.try_recursive_exit(object)) {
1900 // This is a recursive exit which succeeded
1901 return;
1902 }
1903 if (lock_stack.is_recursive(object)) {
1904 // Must inflate recursive locks if try_recursive_exit fails
1905 // This happens for un-structured unlocks, could potentially
1906 // fix try_recursive_exit to handle these.
1907 inflate_fast_locked_object(object, ObjectSynchronizer::inflate_cause_vm_internal, current, current);
1908 }
1909 }
1910
1911 while (mark.is_fast_locked()) {
1912 markWord unlocked_mark = mark.set_unlocked();
1913 markWord old_mark = mark;
1914 mark = object->cas_set_mark(unlocked_mark, old_mark);
1915 if (old_mark == mark) {
1916 // CAS successful, remove from lock_stack
1917 size_t recursion = lock_stack.remove(object) - 1;
1918 assert(recursion == 0, "Should not have unlocked here");
1919 return;
1920 }
1921 }
1922
1923 assert(mark.has_monitor(), "must be");
1924 // The monitor exists
1925 ObjectMonitor* monitor;
1926 if (UseObjectMonitorTable) {
1927 monitor = read_caches(current, lock, object);
1928 if (monitor == nullptr) {
1929 monitor = get_monitor_from_table(object);
1930 }
1931 } else {
1932 monitor = ObjectSynchronizer::read_monitor(mark);
1933 }
1934 if (monitor->has_anonymous_owner()) {
1935 assert(current->lock_stack().contains(object), "current must have object on its lock stack");
1936 monitor->set_owner_from_anonymous(current);
1937 monitor->set_recursions(current->lock_stack().remove(object) - 1);
1938 }
1939
1940 monitor->exit(current);
1941 }
1942
1943 // ObjectSynchronizer::inflate_locked_or_imse is used to get an
1944 // inflated ObjectMonitor* from contexts which require that, such as
1945 // notify/wait and jni_exit. Fast locking keeps the invariant that it
1946 // only inflates if it is already locked by the current thread or the current
1947 // thread is in the process of entering. To maintain this invariant we need to
1948 // throw a java.lang.IllegalMonitorStateException before inflating if the
1949 // current thread is not the owner.
1950 ObjectMonitor* ObjectSynchronizer::inflate_locked_or_imse(oop obj, ObjectSynchronizer::InflateCause cause, TRAPS) {
1951 JavaThread* current = THREAD;
1952
1953 for (;;) {
1954 markWord mark = obj->mark_acquire();
1955 if (mark.is_unlocked()) {
1956 // No lock, IMSE.
1957 THROW_MSG_(vmSymbols::java_lang_IllegalMonitorStateException(),
1958 "current thread is not owner", nullptr);
1959 }
1960
1961 if (mark.is_fast_locked()) {
1962 if (!current->lock_stack().contains(obj)) {
1963 // Fast locked by other thread, IMSE.
1964 THROW_MSG_(vmSymbols::java_lang_IllegalMonitorStateException(),
1965 "current thread is not owner", nullptr);
1966 } else {
1967 // Current thread owns the lock, must inflate
1968 return inflate_fast_locked_object(obj, cause, current, current);
1969 }
1970 }
1971
1972 assert(mark.has_monitor(), "must be");
1973 ObjectMonitor* monitor = ObjectSynchronizer::read_monitor(obj, mark);
1974 if (monitor != nullptr) {
1975 if (monitor->has_anonymous_owner()) {
1976 LockStack& lock_stack = current->lock_stack();
1977 if (lock_stack.contains(obj)) {
1978 // Current thread owns the lock but someone else inflated it.
1979 // Fix owner and pop lock stack.
1980 monitor->set_owner_from_anonymous(current);
1981 monitor->set_recursions(lock_stack.remove(obj) - 1);
1982 } else {
1983 // Fast locked (and inflated) by other thread, or deflation in progress, IMSE.
1984 THROW_MSG_(vmSymbols::java_lang_IllegalMonitorStateException(),
1985 "current thread is not owner", nullptr);
1986 }
1987 }
1988 return monitor;
1989 }
1990 }
1991 }
1992
1993 ObjectMonitor* ObjectSynchronizer::inflate_into_object_header(oop object, ObjectSynchronizer::InflateCause cause, JavaThread* locking_thread, Thread* current) {
1994
1995 // The JavaThread* locking parameter requires that the locking_thread == JavaThread::current,
1996 // or is suspended throughout the call by some other mechanism.
1997 // Even with fast locking the thread might be nullptr when called from a non
1998 // JavaThread. (As may still be the case from FastHashCode). However it is only
1999 // important for the correctness of the fast locking algorithm that the thread
2000 // is set when called from ObjectSynchronizer::enter from the owning thread,
2001 // ObjectSynchronizer::enter_for from any thread, or ObjectSynchronizer::exit.
2002 EventJavaMonitorInflate event;
2003
2004 for (;;) {
2005 const markWord mark = object->mark_acquire();
2006
2007 // The mark can be in one of the following states:
2008 // * inflated - If the ObjectMonitor owner is anonymous and the
2009 // locking_thread owns the object lock, then we make the
2010 // locking_thread the ObjectMonitor owner and remove the
2011 // lock from the locking_thread's lock stack.
2012 // * fast-locked - Coerce it to inflated from fast-locked.
2013 // * unlocked - Aggressively inflate the object.
2014
2015 // CASE: inflated
2016 if (mark.has_monitor()) {
2017 ObjectMonitor* inf = mark.monitor();
2018 markWord dmw = inf->header();
2019 assert(dmw.is_neutral(), "invariant: header=" INTPTR_FORMAT, dmw.value());
2020 if (inf->has_anonymous_owner() &&
2021 locking_thread != nullptr && locking_thread->lock_stack().contains(object)) {
2022 inf->set_owner_from_anonymous(locking_thread);
2023 size_t removed = locking_thread->lock_stack().remove(object);
2024 inf->set_recursions(removed - 1);
2025 }
2026 return inf;
2027 }
2028
2029 // CASE: fast-locked
2030 // Could be fast-locked either by the locking_thread or by some other thread.
2031 //
2032 // Note that we allocate the ObjectMonitor speculatively, _before_
2033 // attempting to set the object's mark to the new ObjectMonitor. If
2034 // the locking_thread owns the monitor, then we set the ObjectMonitor's
2035 // owner to the locking_thread. Otherwise, we set the ObjectMonitor's owner
2036 // to anonymous. If we lose the race to set the object's mark to the
2037 // new ObjectMonitor, then we just delete it and loop around again.
2038 //
2039 if (mark.is_fast_locked()) {
2040 ObjectMonitor* monitor = new ObjectMonitor(object);
2041 monitor->set_header(mark.set_unlocked());
2042 bool own = locking_thread != nullptr && locking_thread->lock_stack().contains(object);
2043 if (own) {
2044 // Owned by locking_thread.
2045 monitor->set_owner(locking_thread);
2046 } else {
2047 // Owned by somebody else.
2048 monitor->set_anonymous_owner();
2049 }
2050 markWord monitor_mark = markWord::encode(monitor);
2051 markWord old_mark = object->cas_set_mark(monitor_mark, mark);
2052 if (old_mark == mark) {
2053 // Success! Return inflated monitor.
2054 if (own) {
2055 size_t removed = locking_thread->lock_stack().remove(object);
2056 monitor->set_recursions(removed - 1);
2057 }
2058 // Once the ObjectMonitor is configured and object is associated
2059 // with the ObjectMonitor, it is safe to allow async deflation:
2060 ObjectSynchronizer::_in_use_list.add(monitor);
2061
2062 log_inflate(current, object, cause);
2063 if (event.should_commit()) {
2064 post_monitor_inflate_event(&event, object, cause);
2065 }
2066 return monitor;
2067 } else {
2068 delete monitor;
2069 continue; // Interference -- just retry
2070 }
2071 }
2072
2073 // CASE: unlocked
2074 // TODO-FIXME: for entry we currently inflate and then try to CAS _owner.
2075 // If we know we're inflating for entry it's better to inflate by swinging a
2076 // pre-locked ObjectMonitor pointer into the object header. A successful
2077 // CAS inflates the object *and* confers ownership to the inflating thread.
2078 // In the current implementation we use a 2-step mechanism where we CAS()
2079 // to inflate and then CAS() again to try to swing _owner from null to current.
2080 // An inflateTry() method that we could call from enter() would be useful.
2081
2082 assert(mark.is_unlocked(), "invariant: header=" INTPTR_FORMAT, mark.value());
2083 ObjectMonitor* m = new ObjectMonitor(object);
2084 // prepare m for installation - set monitor to initial state
2085 m->set_header(mark);
2086
2087 if (object->cas_set_mark(markWord::encode(m), mark) != mark) {
2088 delete m;
2089 m = nullptr;
2090 continue;
2091 // interference - the markword changed - just retry.
2092 // The state-transitions are one-way, so there's no chance of
2093 // live-lock -- "Inflated" is an absorbing state.
2094 }
2095
2096 // Once the ObjectMonitor is configured and object is associated
2097 // with the ObjectMonitor, it is safe to allow async deflation:
2098 ObjectSynchronizer::_in_use_list.add(m);
2099
2100 log_inflate(current, object, cause);
2101 if (event.should_commit()) {
2102 post_monitor_inflate_event(&event, object, cause);
2103 }
2104 return m;
2105 }
2106 }
2107
2108 ObjectMonitor* ObjectSynchronizer::inflate_fast_locked_object(oop object, ObjectSynchronizer::InflateCause cause, JavaThread* locking_thread, JavaThread* current) {
2109 VerifyThreadState vts(locking_thread, current);
2110 assert(locking_thread->lock_stack().contains(object), "locking_thread must have object on its lock stack");
2111
2112 ObjectMonitor* monitor;
2113
2114 if (!UseObjectMonitorTable) {
2115 return inflate_into_object_header(object, cause, locking_thread, current);
2116 }
2117
2118 // Inflating requires a hash code
2119 ObjectSynchronizer::FastHashCode(current, object);
2120
2121 markWord mark = object->mark_acquire();
2122 assert(!mark.is_unlocked(), "Cannot be unlocked");
2123
2124 for (;;) {
2125 // Fetch the monitor from the table
2126 monitor = get_or_insert_monitor(object, current, cause);
2127
2128 // ObjectMonitors are always inserted as anonymously owned, this thread is
2129 // the current holder of the monitor. So unless the entry is stale and
2130 // contains a deflating monitor it must be anonymously owned.
2131 if (monitor->has_anonymous_owner()) {
2132 // The monitor must be anonymously owned if it was added
2133 assert(monitor == get_monitor_from_table(object), "The monitor must be found");
2134 // New fresh monitor
2135 break;
2136 }
2137
2138 // If the monitor was not anonymously owned then we got a deflating monitor
2139 // from the table. We need to let the deflator make progress and remove this
2140 // entry before we are allowed to add a new one.
2141 os::naked_yield();
2142 assert(monitor->is_being_async_deflated(), "Should be the reason");
2143 }
2144
2145 // Set the mark word; loop to handle concurrent updates to other parts of the mark word
2146 while (mark.is_fast_locked()) {
2147 mark = object->cas_set_mark(mark.set_has_monitor(), mark);
2148 }
2149
2150 // Indicate that the monitor now has a known owner
2151 monitor->set_owner_from_anonymous(locking_thread);
2152
2153 // Remove the entry from the thread's lock stack
2154 monitor->set_recursions(locking_thread->lock_stack().remove(object) - 1);
2155
2156 if (locking_thread == current) {
2157 // Only change the thread local state of the current thread.
2158 locking_thread->om_set_monitor_cache(monitor);
2159 }
2160
2161 return monitor;
2162 }
2163
2164 ObjectMonitor* ObjectSynchronizer::inflate_and_enter(oop object, BasicLock* lock, ObjectSynchronizer::InflateCause cause, JavaThread* locking_thread, JavaThread* current) {
2165 VerifyThreadState vts(locking_thread, current);
2166
2167 // Note: In some paths (deoptimization) the 'current' thread inflates and
2168 // enters the lock on behalf of the 'locking_thread' thread.
2169
2170 ObjectMonitor* monitor = nullptr;
2171
2172 if (!UseObjectMonitorTable) {
2173 // Do the old inflate and enter.
2174 monitor = inflate_into_object_header(object, cause, locking_thread, current);
2175
2176 bool entered;
2177 if (locking_thread == current) {
2178 entered = monitor->enter(locking_thread);
2179 } else {
2180 entered = monitor->enter_for(locking_thread);
2181 }
2182
2183 // enter returns false for deflation found.
2184 return entered ? monitor : nullptr;
2185 }
2186
2187 NoSafepointVerifier nsv;
2188
2189 // Try to get the monitor from the thread-local cache.
2190 // There's no need to use the cache if we are locking
2191 // on behalf of another thread.
2192 if (current == locking_thread) {
2193 monitor = read_caches(current, lock, object);
2194 }
2195
2196 // Get or create the monitor
2197 if (monitor == nullptr) {
2198 // Lightweight monitors require that hash codes are installed first
2199 ObjectSynchronizer::FastHashCode(locking_thread, object);
2200 monitor = get_or_insert_monitor(object, current, cause);
2201 }
2202
2203 if (monitor->try_enter(locking_thread)) {
2204 return monitor;
2205 }
2206
2207 // Holds is_being_async_deflated() stable throughout this function.
2208 ObjectMonitorContentionMark contention_mark(monitor);
2209
2210 /// First handle the case where the monitor from the table is deflated
2211 if (monitor->is_being_async_deflated()) {
2212 // The MonitorDeflation thread is deflating the monitor. The locking thread
2213 // must spin until further progress has been made.
2214
2215 // Clear the BasicLock cache as it may contain this monitor.
2216 lock->clear_object_monitor_cache();
2217
2218 const markWord mark = object->mark_acquire();
2219
2220 if (mark.has_monitor()) {
2221 // Waiting on the deflation thread to remove the deflated monitor from the table.
2222 os::naked_yield();
2223
2224 } else if (mark.is_fast_locked()) {
2225 // Some other thread managed to fast-lock the lock, or this is a
2226 // recursive lock from the same thread; yield for the deflation
2227 // thread to remove the deflated monitor from the table.
2228 os::naked_yield();
2229
2230 } else {
2231 assert(mark.is_unlocked(), "Implied");
2232 // Retry immediately
2233 }
2234
2235 // Retry
2236 return nullptr;
2237 }
2238
2239 for (;;) {
2240 const markWord mark = object->mark_acquire();
2241 // The mark can be in one of the following states:
2242 // * inflated - If the ObjectMonitor owner is anonymous
2243 // and the locking_thread owns the object
2244 // lock, then we make the locking_thread
2245 // the ObjectMonitor owner and remove the
2246 // lock from the locking_thread's lock stack.
2247 // * fast-locked - Coerce it to inflated from fast-locked.
2248 // * neutral - Inflate the object. Successful CAS is locked
2249
2250 // CASE: inflated
2251 if (mark.has_monitor()) {
2252 LockStack& lock_stack = locking_thread->lock_stack();
2253 if (monitor->has_anonymous_owner() && lock_stack.contains(object)) {
2254 // The lock is fast-locked by the locking thread,
2255 // convert it to a held monitor with a known owner.
2256 monitor->set_owner_from_anonymous(locking_thread);
2257 monitor->set_recursions(lock_stack.remove(object) - 1);
2258 }
2259
2260 break; // Success
2261 }
2262
2263 // CASE: fast-locked
2264 // Could be fast-locked either by locking_thread or by some other thread.
2265 //
2266 if (mark.is_fast_locked()) {
2267 markWord old_mark = object->cas_set_mark(mark.set_has_monitor(), mark);
2268 if (old_mark != mark) {
2269 // CAS failed
2270 continue;
2271 }
2272
2273 // Success! Return inflated monitor.
2274 LockStack& lock_stack = locking_thread->lock_stack();
2275 if (lock_stack.contains(object)) {
2276 // The lock is fast-locked by the locking thread,
2277 // convert it to a held monitor with a known owner.
2278 monitor->set_owner_from_anonymous(locking_thread);
2279 monitor->set_recursions(lock_stack.remove(object) - 1);
2280 }
2281
2282 break; // Success
2283 }
2284
2285 // CASE: neutral (unlocked)
2286
2287 // Catch if the object's header is not neutral (not locked and
2288 // not marked is what we care about here).
2289 assert(mark.is_neutral(), "invariant: header=" INTPTR_FORMAT, mark.value());
2290 markWord old_mark = object->cas_set_mark(mark.set_has_monitor(), mark);
2291 if (old_mark != mark) {
2292 // CAS failed
2293 continue;
2294 }
2295
2296 // Transitioned from unlocked to monitor means locking_thread owns the lock.
2297 monitor->set_owner_from_anonymous(locking_thread);
2298
2299 return monitor;
2300 }
2301
2302 if (current == locking_thread) {
2303 // One round of spinning
2304 if (monitor->spin_enter(locking_thread)) {
2305 return monitor;
2306 }
2307
2308 // Monitor is contended, take the time before entering to fix the lock stack.
2309 LockStackInflateContendedLocks().inflate(current);
2310 }
2311
2312 // enter can block for safepoints; clear the unhandled object oop
2313 PauseNoSafepointVerifier pnsv(&nsv);
2314 object = nullptr;
2315
2316 if (current == locking_thread) {
2317 monitor->enter_with_contention_mark(locking_thread, contention_mark);
2318 } else {
2319 monitor->enter_for_with_contention_mark(locking_thread, contention_mark);
2320 }
2321
2322 return monitor;
2323 }
2324
2325 void ObjectSynchronizer::deflate_monitor(oop obj, ObjectMonitor* monitor) {
2326 if (obj != nullptr) {
2327 deflate_mark_word(obj);
2328 remove_monitor(monitor, obj);
2329 }
2330 }
2331
2332 ObjectMonitor* ObjectSynchronizer::get_monitor_from_table(oop obj) {
2333 assert(UseObjectMonitorTable, "must be");
2334 return ObjectMonitorTable::monitor_get(obj);
2335 }
2336
2337 ObjectMonitor* ObjectSynchronizer::read_monitor(markWord mark) {
2338 return mark.monitor();
2339 }
2340
2341 ObjectMonitor* ObjectSynchronizer::read_monitor(oop obj) {
2342 return ObjectSynchronizer::read_monitor(obj, obj->mark());
2343 }
2344
2345 ObjectMonitor* ObjectSynchronizer::read_monitor(oop obj, markWord mark) {
2346 if (!UseObjectMonitorTable) {
2347 return read_monitor(mark);
2348 } else {
2349 return ObjectSynchronizer::get_monitor_from_table(obj);
2350 }
2351 }
2352
2353 bool ObjectSynchronizer::quick_enter_internal(oop obj, BasicLock* lock, JavaThread* current) {
2354 assert(current->thread_state() == _thread_in_Java, "must be");
2355 assert(obj != nullptr, "must be");
2356 NoSafepointVerifier nsv;
2357
2358 LockStack& lock_stack = current->lock_stack();
2359 if (lock_stack.is_full()) {
2360 // Always go into runtime if the lock stack is full.
2361 return false;
2362 }
2363
2364 const markWord mark = obj->mark();
2365
2366 #ifndef _LP64
2367 // Only for 32bit which has limited support for fast locking outside the runtime.
2368 if (lock_stack.try_recursive_enter(obj)) {
2369 // Recursive lock successful.
2370 return true;
2371 }
2372
2373 if (mark.is_unlocked()) {
2374 markWord locked_mark = mark.set_fast_locked();
2375 if (obj->cas_set_mark(locked_mark, mark) == mark) {
2376 // Successfully fast-locked, push object to lock-stack and return.
2377 lock_stack.push(obj);
2378 return true;
2379 }
2380 }
2381 #endif
2382
2383 if (mark.has_monitor()) {
2384 ObjectMonitor* monitor;
2385 if (UseObjectMonitorTable) {
2386 monitor = read_caches(current, lock, obj);
2387 } else {
2388 monitor = ObjectSynchronizer::read_monitor(mark);
2389 }
2390
2391 if (monitor == nullptr) {
2392 // Take the slow-path on a cache miss.
2393 return false;
2394 }
2395
2396 if (UseObjectMonitorTable) {
2397 // Set the monitor regardless of success.
2398 // Either we successfully lock on the monitor, or we retry with the
2399 // monitor in the slow path. If the monitor gets deflated, it will be
2400 // cleared, either by the CacheSetter if we fast lock in enter or in
2401 // inflate_and_enter when we see that the monitor is deflated.
2402 lock->set_object_monitor_cache(monitor);
2403 }
2404
2405 if (monitor->spin_enter(current)) {
2406 return true;
2407 }
2408 }
2409
2410 // Slow-path.
2411 return false;
2412 }
2413
2414 bool ObjectSynchronizer::quick_enter(oop obj, BasicLock* lock, JavaThread* current) {
2415 assert(current->thread_state() == _thread_in_Java, "invariant");
2416 NoSafepointVerifier nsv;
2417 if (obj == nullptr) return false; // Need to throw NPE
2418
2419 if (obj->klass()->is_value_based()) {
2420 return false;
2421 }
2422
2423 return ObjectSynchronizer::quick_enter_internal(obj, lock, current);
2424 }