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