2 * Copyright (C) 2008 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
21 #include "base/mutex.h"
22 #include "base/stl_util.h"
23 #include "class_linker.h"
24 #include "dex_file-inl.h"
25 #include "dex_instruction.h"
26 #include "lock_word-inl.h"
27 #include "mirror/art_method-inl.h"
28 #include "mirror/class-inl.h"
29 #include "mirror/object-inl.h"
30 #include "mirror/object_array-inl.h"
31 #include "object_utils.h"
32 #include "scoped_thread_state_change.h"
34 #include "thread_list.h"
35 #include "verifier/method_verifier.h"
36 #include "well_known_classes.h"
41 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
42 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
43 * or b) wait() is called on the Object.
45 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
46 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
47 * though, because we have a full 32 bits to work with.
49 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
50 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
51 * a lock has been inflated it remains in the "fat" state indefinitely.
53 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
54 * in the LockWord value type.
57 * - mutually exclusive access to resources
58 * - a way for multiple threads to wait for notification
60 * In effect, they fill the role of both mutexes and condition variables.
62 * Only one thread can own the monitor at any time. There may be several threads waiting on it
63 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
67 bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
68 uint32_t Monitor::lock_profiling_threshold_ = 0;
70 bool Monitor::IsSensitiveThread() {
71 if (is_sensitive_thread_hook_ != NULL) {
72 return (*is_sensitive_thread_hook_)();
77 void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
78 lock_profiling_threshold_ = lock_profiling_threshold;
79 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
82 Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
83 : monitor_lock_("a monitor lock", kMonitorLock),
84 monitor_contenders_("monitor contenders", monitor_lock_),
90 hash_code_(hash_code),
91 locking_method_(NULL),
93 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
95 DCHECK(false) << "Should not be reached in 64b";
98 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
99 // with the owner unlocking the thin-lock.
100 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
101 // The identity hash code is set for the life time of the monitor.
104 Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
106 : monitor_lock_("a monitor lock", kMonitorLock),
107 monitor_contenders_("monitor contenders", monitor_lock_),
113 hash_code_(hash_code),
114 locking_method_(NULL),
118 next_free_ = nullptr;
120 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
121 // with the owner unlocking the thin-lock.
122 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
123 // The identity hash code is set for the life time of the monitor.
126 int32_t Monitor::GetHashCode() {
127 while (!HasHashCode()) {
128 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
132 DCHECK(HasHashCode());
133 return hash_code_.LoadRelaxed();
136 bool Monitor::Install(Thread* self) {
137 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
138 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
139 // Propagate the lock state.
140 LockWord lw(GetObject()->GetLockWord(false));
141 switch (lw.GetState()) {
142 case LockWord::kThinLocked: {
143 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
144 lock_count_ = lw.ThinLockCount();
147 case LockWord::kHashCode: {
148 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
151 case LockWord::kFatLocked: {
152 // The owner_ is suspended but another thread beat us to install a monitor.
155 case LockWord::kUnlocked: {
156 LOG(FATAL) << "Inflating unlocked lock word";
160 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
165 // Publish the updated lock word, which may race with other threads.
166 bool success = GetObject()->CasLockWord(lw, fat);
168 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
169 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_);
174 Monitor::~Monitor() {
175 // Deflated monitors have a null object.
179 * Links a thread into a monitor's wait set. The monitor lock must be
180 * held by the caller of this routine.
182 void Monitor::AppendToWaitSet(Thread* thread) {
183 DCHECK(owner_ == Thread::Current());
184 DCHECK(thread != NULL);
185 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
186 if (wait_set_ == NULL) {
192 Thread* t = wait_set_;
193 while (t->GetWaitNext() != nullptr) {
194 t = t->GetWaitNext();
196 t->SetWaitNext(thread);
200 * Unlinks a thread from a monitor's wait set. The monitor lock must
201 * be held by the caller of this routine.
203 void Monitor::RemoveFromWaitSet(Thread *thread) {
204 DCHECK(owner_ == Thread::Current());
205 DCHECK(thread != NULL);
206 if (wait_set_ == NULL) {
209 if (wait_set_ == thread) {
210 wait_set_ = thread->GetWaitNext();
211 thread->SetWaitNext(nullptr);
215 Thread* t = wait_set_;
216 while (t->GetWaitNext() != NULL) {
217 if (t->GetWaitNext() == thread) {
218 t->SetWaitNext(thread->GetWaitNext());
219 thread->SetWaitNext(nullptr);
222 t = t->GetWaitNext();
226 void Monitor::SetObject(mirror::Object* object) {
230 void Monitor::Lock(Thread* self) {
231 MutexLock mu(self, monitor_lock_);
233 if (owner_ == nullptr) { // Unowned.
235 CHECK_EQ(lock_count_, 0);
236 // When debugging, save the current monitor holder for future
237 // acquisition failures to use in sampled logging.
238 if (lock_profiling_threshold_ != 0) {
239 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
242 } else if (owner_ == self) { // Recursive.
247 const bool log_contention = (lock_profiling_threshold_ != 0);
248 uint64_t wait_start_ms = log_contention ? 0 : MilliTime();
249 mirror::ArtMethod* owners_method = locking_method_;
250 uint32_t owners_dex_pc = locking_dex_pc_;
251 // Do this before releasing the lock so that we don't get deflated.
253 monitor_lock_.Unlock(self); // Let go of locks in order.
254 self->SetMonitorEnterObject(GetObject());
256 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
257 MutexLock mu2(self, monitor_lock_); // Reacquire monitor_lock_ without mutator_lock_ for Wait.
258 if (owner_ != NULL) { // Did the owner_ give the lock up?
259 monitor_contenders_.Wait(self); // Still contended so wait.
260 // Woken from contention.
261 if (log_contention) {
262 uint64_t wait_ms = MilliTime() - wait_start_ms;
263 uint32_t sample_percent;
264 if (wait_ms >= lock_profiling_threshold_) {
265 sample_percent = 100;
267 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
269 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
270 const char* owners_filename;
271 uint32_t owners_line_number;
272 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
273 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
278 self->SetMonitorEnterObject(nullptr);
279 monitor_lock_.Lock(self); // Reacquire locks in order.
284 static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
285 __attribute__((format(printf, 1, 2)));
287 static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
288 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
291 Thread* self = Thread::Current();
292 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
293 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
294 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
295 std::ostringstream ss;
297 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
298 << self->GetException(NULL)->Dump() << "\n" << ss.str();
303 static std::string ThreadToString(Thread* thread) {
304 if (thread == NULL) {
307 std::ostringstream oss;
308 // TODO: alternatively, we could just return the thread's name.
313 void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
315 Thread* current_owner = NULL;
316 std::string current_owner_string;
317 std::string expected_owner_string;
318 std::string found_owner_string;
320 // TODO: isn't this too late to prevent threads from disappearing?
321 // Acquire thread list lock so threads won't disappear from under us.
322 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
323 // Re-read owner now that we hold lock.
324 current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
325 // Get short descriptions of the threads involved.
326 current_owner_string = ThreadToString(current_owner);
327 expected_owner_string = ThreadToString(expected_owner);
328 found_owner_string = ThreadToString(found_owner);
330 if (current_owner == NULL) {
331 if (found_owner == NULL) {
332 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
334 PrettyTypeOf(o).c_str(),
335 expected_owner_string.c_str());
337 // Race: the original read found an owner but now there is none
338 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
339 " (where now the monitor appears unowned) on thread '%s'",
340 found_owner_string.c_str(),
341 PrettyTypeOf(o).c_str(),
342 expected_owner_string.c_str());
345 if (found_owner == NULL) {
346 // Race: originally there was no owner, there is now
347 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
348 " (originally believed to be unowned) on thread '%s'",
349 current_owner_string.c_str(),
350 PrettyTypeOf(o).c_str(),
351 expected_owner_string.c_str());
353 if (found_owner != current_owner) {
354 // Race: originally found and current owner have changed
355 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
356 " owned by '%s') on object of type '%s' on thread '%s'",
357 found_owner_string.c_str(),
358 current_owner_string.c_str(),
359 PrettyTypeOf(o).c_str(),
360 expected_owner_string.c_str());
362 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
364 current_owner_string.c_str(),
365 PrettyTypeOf(o).c_str(),
366 expected_owner_string.c_str());
372 bool Monitor::Unlock(Thread* self) {
373 DCHECK(self != NULL);
374 MutexLock mu(self, monitor_lock_);
375 Thread* owner = owner_;
377 // We own the monitor, so nobody else can be in here.
378 if (lock_count_ == 0) {
380 locking_method_ = NULL;
383 monitor_contenders_.Signal(self);
388 // We don't own this, so we're not allowed to unlock it.
389 // The JNI spec says that we should throw IllegalMonitorStateException
391 FailedUnlock(GetObject(), self, owner, this);
398 * Wait on a monitor until timeout, interrupt, or notification. Used for
399 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
401 * If another thread calls Thread.interrupt(), we throw InterruptedException
402 * and return immediately if one of the following are true:
403 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
404 * - blocked in join(), join(long), or join(long, int) methods of Thread
405 * - blocked in sleep(long), or sleep(long, int) methods of Thread
406 * Otherwise, we set the "interrupted" flag.
408 * Checks to make sure that "ns" is in the range 0-999999
409 * (i.e. fractions of a millisecond) and throws the appropriate
410 * exception if it isn't.
412 * The spec allows "spurious wakeups", and recommends that all code using
413 * Object.wait() do so in a loop. This appears to derive from concerns
414 * about pthread_cond_wait() on multiprocessor systems. Some commentary
415 * on the web casts doubt on whether these can/should occur.
417 * Since we're allowed to wake up "early", we clamp extremely long durations
418 * to return at the end of the 32-bit time epoch.
420 void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
421 bool interruptShouldThrow, ThreadState why) {
422 DCHECK(self != NULL);
423 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
425 monitor_lock_.Lock(self);
427 // Make sure that we hold the lock.
428 if (owner_ != self) {
429 monitor_lock_.Unlock(self);
430 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
434 // We need to turn a zero-length timed wait into a regular wait because
435 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
436 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
440 // Enforce the timeout range.
441 if (ms < 0 || ns < 0 || ns > 999999) {
442 monitor_lock_.Unlock(self);
443 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
444 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
445 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
450 * Add ourselves to the set of threads waiting on this monitor, and
451 * release our hold. We need to let it go even if we're a few levels
452 * deep in a recursive lock, and we need to restore that later.
454 * We append to the wait set ahead of clearing the count and owner
455 * fields so the subroutine can check that the calling thread owns
456 * the monitor. Aside from that, the order of member updates is
457 * not order sensitive as we hold the pthread mutex.
459 AppendToWaitSet(self);
461 int prev_lock_count = lock_count_;
464 mirror::ArtMethod* saved_method = locking_method_;
465 locking_method_ = NULL;
466 uintptr_t saved_dex_pc = locking_dex_pc_;
470 * Update thread state. If the GC wakes up, it'll ignore us, knowing
471 * that we won't touch any references in this state, and we'll check
472 * our suspend mode before we transition out.
474 self->TransitionFromRunnableToSuspended(why);
476 bool was_interrupted = false;
478 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
479 MutexLock mu(self, *self->GetWaitMutex());
481 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
482 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
484 DCHECK(self->GetWaitMonitor() == nullptr);
485 self->SetWaitMonitor(this);
487 // Release the monitor lock.
488 monitor_contenders_.Signal(self);
489 monitor_lock_.Unlock(self);
491 // Handle the case where the thread was interrupted before we called wait().
492 if (self->IsInterruptedLocked()) {
493 was_interrupted = true;
495 // Wait for a notification or a timeout to occur.
496 if (why == kWaiting) {
497 self->GetWaitConditionVariable()->Wait(self);
499 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
500 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
502 if (self->IsInterruptedLocked()) {
503 was_interrupted = true;
505 self->SetInterruptedLocked(false);
509 // Set self->status back to kRunnable, and self-suspend if needed.
510 self->TransitionFromSuspendedToRunnable();
513 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
514 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
515 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
516 // are waiting on "null".)
517 MutexLock mu(self, *self->GetWaitMutex());
518 DCHECK(self->GetWaitMonitor() != nullptr);
519 self->SetWaitMonitor(nullptr);
522 // Re-acquire the monitor and lock.
524 monitor_lock_.Lock(self);
525 self->GetWaitMutex()->AssertNotHeld(self);
528 * We remove our thread from wait set after restoring the count
529 * and owner fields so the subroutine can check that the calling
530 * thread owns the monitor. Aside from that, the order of member
531 * updates is not order sensitive as we hold the pthread mutex.
534 lock_count_ = prev_lock_count;
535 locking_method_ = saved_method;
536 locking_dex_pc_ = saved_dex_pc;
538 RemoveFromWaitSet(self);
540 monitor_lock_.Unlock(self);
542 if (was_interrupted) {
544 * We were interrupted while waiting, or somebody interrupted an
545 * un-interruptible thread earlier and we're bailing out immediately.
547 * The doc sayeth: "The interrupted status of the current thread is
548 * cleared when this exception is thrown."
551 MutexLock mu(self, *self->GetWaitMutex());
552 self->SetInterruptedLocked(false);
554 if (interruptShouldThrow) {
555 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
556 self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
561 void Monitor::Notify(Thread* self) {
562 DCHECK(self != NULL);
563 MutexLock mu(self, monitor_lock_);
564 // Make sure that we hold the lock.
565 if (owner_ != self) {
566 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
569 // Signal the first waiting thread in the wait set.
570 while (wait_set_ != NULL) {
571 Thread* thread = wait_set_;
572 wait_set_ = thread->GetWaitNext();
573 thread->SetWaitNext(nullptr);
575 // Check to see if the thread is still waiting.
576 MutexLock mu(self, *thread->GetWaitMutex());
577 if (thread->GetWaitMonitor() != nullptr) {
578 thread->GetWaitConditionVariable()->Signal(self);
584 void Monitor::NotifyAll(Thread* self) {
585 DCHECK(self != NULL);
586 MutexLock mu(self, monitor_lock_);
587 // Make sure that we hold the lock.
588 if (owner_ != self) {
589 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
592 // Signal all threads in the wait set.
593 while (wait_set_ != NULL) {
594 Thread* thread = wait_set_;
595 wait_set_ = thread->GetWaitNext();
596 thread->SetWaitNext(nullptr);
601 bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
602 DCHECK(obj != nullptr);
603 // Don't need volatile since we only deflate with mutators suspended.
604 LockWord lw(obj->GetLockWord(false));
605 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
606 if (lw.GetState() == LockWord::kFatLocked) {
607 Monitor* monitor = lw.FatLockMonitor();
608 DCHECK(monitor != nullptr);
609 MutexLock mu(self, monitor->monitor_lock_);
610 // Can't deflate if we have anybody waiting on the CV.
611 if (monitor->num_waiters_ > 0) {
614 Thread* owner = monitor->owner_;
615 if (owner != nullptr) {
616 // Can't deflate if we are locked and have a hash code.
617 if (monitor->HasHashCode()) {
620 // Can't deflate if our lock count is too high.
621 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
624 // Deflate to a thin lock.
625 obj->SetLockWord(LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_), false);
626 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
627 << monitor->lock_count_;
628 } else if (monitor->HasHashCode()) {
629 obj->SetLockWord(LockWord::FromHashCode(monitor->GetHashCode()), false);
630 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
632 // No lock and no hash, just put an empty lock word inside the object.
633 obj->SetLockWord(LockWord(), false);
634 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
636 // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
638 monitor->obj_ = nullptr;
644 * Changes the shape of a monitor from thin to fat, preserving the internal lock state. The calling
645 * thread must own the lock or the owner must be suspended. There's a race with other threads
646 * inflating the lock and so the caller should read the monitor following the call.
648 void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
649 DCHECK(self != nullptr);
650 DCHECK(obj != nullptr);
651 // Allocate and acquire a new monitor.
652 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
653 DCHECK(m != nullptr);
654 if (m->Install(self)) {
655 if (owner != nullptr) {
656 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
657 << " created monitor " << m << " for object " << obj;
659 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
660 << " created monitor " << m << " for object " << obj;
662 Runtime::Current()->GetMonitorList()->Add(m);
663 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
665 MonitorPool::ReleaseMonitor(self, m);
669 void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
670 uint32_t hash_code) {
671 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
672 uint32_t owner_thread_id = lock_word.ThinLockOwner();
673 if (owner_thread_id == self->GetThreadId()) {
674 // We own the monitor, we can easily inflate it.
675 Inflate(self, self, obj.Get(), hash_code);
677 ThreadList* thread_list = Runtime::Current()->GetThreadList();
678 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
679 self->SetMonitorEnterObject(obj.Get());
683 ScopedThreadStateChange tsc(self, kBlocked);
684 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
686 if (owner != nullptr) {
687 // We succeeded in suspending the thread, check the lock's status didn't change.
688 lock_word = obj->GetLockWord(true);
689 if (lock_word.GetState() == LockWord::kThinLocked &&
690 lock_word.ThinLockOwner() == owner_thread_id) {
691 // Go ahead and inflate the lock.
692 Inflate(self, owner, obj.Get(), hash_code);
694 thread_list->Resume(owner, false);
696 self->SetMonitorEnterObject(nullptr);
700 // Fool annotalysis into thinking that the lock on obj is acquired.
701 static mirror::Object* FakeLock(mirror::Object* obj)
702 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
706 // Fool annotalysis into thinking that the lock on obj is release.
707 static mirror::Object* FakeUnlock(mirror::Object* obj)
708 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
712 mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
713 DCHECK(self != NULL);
716 uint32_t thread_id = self->GetThreadId();
717 size_t contention_count = 0;
718 StackHandleScope<1> hs(self);
719 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
721 LockWord lock_word = h_obj->GetLockWord(true);
722 switch (lock_word.GetState()) {
723 case LockWord::kUnlocked: {
724 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
725 if (h_obj->CasLockWord(lock_word, thin_locked)) {
726 // CasLockWord enforces more than the acquire ordering we need here.
727 return h_obj.Get(); // Success!
729 continue; // Go again.
731 case LockWord::kThinLocked: {
732 uint32_t owner_thread_id = lock_word.ThinLockOwner();
733 if (owner_thread_id == thread_id) {
734 // We own the lock, increase the recursion count.
735 uint32_t new_count = lock_word.ThinLockCount() + 1;
736 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
737 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
738 h_obj->SetLockWord(thin_locked, true);
739 return h_obj.Get(); // Success!
741 // We'd overflow the recursion count, so inflate the monitor.
742 InflateThinLocked(self, h_obj, lock_word, 0);
747 Runtime* runtime = Runtime::Current();
748 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
749 NanoSleep(1000); // Sleep for 1us and re-attempt.
751 contention_count = 0;
752 InflateThinLocked(self, h_obj, lock_word, 0);
755 continue; // Start from the beginning.
757 case LockWord::kFatLocked: {
758 Monitor* mon = lock_word.FatLockMonitor();
760 return h_obj.Get(); // Success!
762 case LockWord::kHashCode:
763 // Inflate with the existing hashcode.
764 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
765 continue; // Start from the beginning.
767 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
774 bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
775 DCHECK(self != NULL);
777 obj = FakeUnlock(obj);
778 LockWord lock_word = obj->GetLockWord(true);
779 StackHandleScope<1> hs(self);
780 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
781 switch (lock_word.GetState()) {
782 case LockWord::kHashCode:
784 case LockWord::kUnlocked:
785 FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
786 return false; // Failure.
787 case LockWord::kThinLocked: {
788 uint32_t thread_id = self->GetThreadId();
789 uint32_t owner_thread_id = lock_word.ThinLockOwner();
790 if (owner_thread_id != thread_id) {
791 // TODO: there's a race here with the owner dying while we unlock.
793 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
794 FailedUnlock(h_obj.Get(), self, owner, nullptr);
795 return false; // Failure.
797 // We own the lock, decrease the recursion count.
798 if (lock_word.ThinLockCount() != 0) {
799 uint32_t new_count = lock_word.ThinLockCount() - 1;
800 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
801 h_obj->SetLockWord(thin_locked, true);
803 h_obj->SetLockWord(LockWord(), true);
805 return true; // Success!
808 case LockWord::kFatLocked: {
809 Monitor* mon = lock_word.FatLockMonitor();
810 return mon->Unlock(self);
813 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
820 * Object.wait(). Also called for class init.
822 void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
823 bool interruptShouldThrow, ThreadState why) {
824 DCHECK(self != nullptr);
825 DCHECK(obj != nullptr);
826 LockWord lock_word = obj->GetLockWord(true);
827 switch (lock_word.GetState()) {
828 case LockWord::kHashCode:
830 case LockWord::kUnlocked:
831 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
833 case LockWord::kThinLocked: {
834 uint32_t thread_id = self->GetThreadId();
835 uint32_t owner_thread_id = lock_word.ThinLockOwner();
836 if (owner_thread_id != thread_id) {
837 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
840 // We own the lock, inflate to enqueue ourself on the Monitor.
841 Inflate(self, self, obj, 0);
842 lock_word = obj->GetLockWord(true);
846 case LockWord::kFatLocked:
847 break; // Already set for a wait.
849 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
853 Monitor* mon = lock_word.FatLockMonitor();
854 mon->Wait(self, ms, ns, interruptShouldThrow, why);
857 void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
858 DCHECK(self != nullptr);
859 DCHECK(obj != nullptr);
860 LockWord lock_word = obj->GetLockWord(true);
861 switch (lock_word.GetState()) {
862 case LockWord::kHashCode:
864 case LockWord::kUnlocked:
865 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
867 case LockWord::kThinLocked: {
868 uint32_t thread_id = self->GetThreadId();
869 uint32_t owner_thread_id = lock_word.ThinLockOwner();
870 if (owner_thread_id != thread_id) {
871 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
874 // We own the lock but there's no Monitor and therefore no waiters.
878 case LockWord::kFatLocked: {
879 Monitor* mon = lock_word.FatLockMonitor();
881 mon->NotifyAll(self);
888 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
894 uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
895 DCHECK(obj != nullptr);
896 LockWord lock_word = obj->GetLockWord(true);
897 switch (lock_word.GetState()) {
898 case LockWord::kHashCode:
900 case LockWord::kUnlocked:
901 return ThreadList::kInvalidThreadId;
902 case LockWord::kThinLocked:
903 return lock_word.ThinLockOwner();
904 case LockWord::kFatLocked: {
905 Monitor* mon = lock_word.FatLockMonitor();
906 return mon->GetOwnerThreadId();
909 LOG(FATAL) << "Unreachable";
910 return ThreadList::kInvalidThreadId;
915 void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
916 // Determine the wait message and object we're waiting or blocked upon.
917 mirror::Object* pretty_object = nullptr;
918 const char* wait_message = nullptr;
919 uint32_t lock_owner = ThreadList::kInvalidThreadId;
920 ThreadState state = thread->GetState();
921 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
922 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
923 Thread* self = Thread::Current();
924 MutexLock mu(self, *thread->GetWaitMutex());
925 Monitor* monitor = thread->GetWaitMonitor();
926 if (monitor != nullptr) {
927 pretty_object = monitor->GetObject();
929 } else if (state == kBlocked) {
930 wait_message = " - waiting to lock ";
931 pretty_object = thread->GetMonitorEnterObject();
932 if (pretty_object != nullptr) {
933 lock_owner = pretty_object->GetLockOwnerThreadId();
937 if (wait_message != nullptr) {
938 if (pretty_object == nullptr) {
939 os << wait_message << "an unknown object";
941 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
942 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
943 // Getting the identity hashcode here would result in lock inflation and suspension of the
944 // current thread, which isn't safe if this is the only runnable thread.
945 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
946 reinterpret_cast<intptr_t>(pretty_object),
947 PrettyTypeOf(pretty_object).c_str());
949 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
950 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
951 PrettyTypeOf(pretty_object).c_str());
954 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
955 if (lock_owner != ThreadList::kInvalidThreadId) {
956 os << " held by thread " << lock_owner;
962 mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
963 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
964 // definition of contended that includes a monitor a thread is trying to enter...
965 mirror::Object* result = thread->GetMonitorEnterObject();
966 if (result == NULL) {
967 // ...but also a monitor that the thread is waiting on.
968 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
969 Monitor* monitor = thread->GetWaitMonitor();
970 if (monitor != NULL) {
971 result = monitor->GetObject();
977 void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
978 void* callback_context) {
979 mirror::ArtMethod* m = stack_visitor->GetMethod();
982 // Native methods are an easy special case.
983 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
985 if (m->IsSynchronized()) {
986 mirror::Object* jni_this = stack_visitor->GetCurrentHandleScope()->GetReference(0);
987 callback(jni_this, callback_context);
992 // Proxy methods should not be synchronized.
993 if (m->IsProxyMethod()) {
994 CHECK(!m->IsSynchronized());
998 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
999 if (m->IsClassInitializer()) {
1000 callback(m->GetDeclaringClass(), callback_context);
1001 // Fall through because there might be synchronization in the user code too.
1004 // Is there any reason to believe there's any synchronization in this method?
1005 const DexFile::CodeItem* code_item = m->GetCodeItem();
1006 CHECK(code_item != NULL) << PrettyMethod(m);
1007 if (code_item->tries_size_ == 0) {
1008 return; // No "tries" implies no synchronization, so no held locks to report.
1011 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1012 // the locks held in this stack frame.
1013 std::vector<uint32_t> monitor_enter_dex_pcs;
1014 verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), &monitor_enter_dex_pcs);
1015 if (monitor_enter_dex_pcs.empty()) {
1019 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
1020 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1021 // We want the registers used by those instructions (so we can read the values out of them).
1022 uint32_t dex_pc = monitor_enter_dex_pcs[i];
1023 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
1025 // Quick sanity check.
1026 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
1027 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
1028 << reinterpret_cast<void*>(monitor_enter_instruction);
1031 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
1032 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
1034 callback(o, callback_context);
1038 bool Monitor::IsValidLockWord(LockWord lock_word) {
1039 switch (lock_word.GetState()) {
1040 case LockWord::kUnlocked:
1041 // Nothing to check.
1043 case LockWord::kThinLocked:
1044 // Basic sanity check of owner.
1045 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1046 case LockWord::kFatLocked: {
1047 // Check the monitor appears in the monitor list.
1048 Monitor* mon = lock_word.FatLockMonitor();
1049 MonitorList* list = Runtime::Current()->GetMonitorList();
1050 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1051 for (Monitor* list_mon : list->list_) {
1052 if (mon == list_mon) {
1053 return true; // Found our monitor.
1056 return false; // Fail - unowned monitor in an object.
1058 case LockWord::kHashCode:
1061 LOG(FATAL) << "Unreachable";
1066 bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1067 MutexLock mu(Thread::Current(), monitor_lock_);
1068 return owner_ != nullptr;
1071 void Monitor::TranslateLocation(mirror::ArtMethod* method, uint32_t dex_pc,
1072 const char** source_file, uint32_t* line_number) const {
1073 // If method is null, location is unknown
1074 if (method == NULL) {
1079 *source_file = method->GetDeclaringClassSourceFile();
1080 if (*source_file == NULL) {
1083 *line_number = method->GetLineNumFromDexPC(dex_pc);
1086 uint32_t Monitor::GetOwnerThreadId() {
1087 MutexLock mu(Thread::Current(), monitor_lock_);
1088 Thread* owner = owner_;
1089 if (owner != NULL) {
1090 return owner->GetThreadId();
1092 return ThreadList::kInvalidThreadId;
1096 MonitorList::MonitorList()
1097 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
1098 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
1101 MonitorList::~MonitorList() {
1102 Thread* self = Thread::Current();
1103 MutexLock mu(self, monitor_list_lock_);
1104 // Release all monitors to the pool.
1105 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1106 // clear faster in the pool.
1107 MonitorPool::ReleaseMonitors(self, &list_);
1110 void MonitorList::DisallowNewMonitors() {
1111 MutexLock mu(Thread::Current(), monitor_list_lock_);
1112 allow_new_monitors_ = false;
1115 void MonitorList::AllowNewMonitors() {
1116 Thread* self = Thread::Current();
1117 MutexLock mu(self, monitor_list_lock_);
1118 allow_new_monitors_ = true;
1119 monitor_add_condition_.Broadcast(self);
1122 void MonitorList::Add(Monitor* m) {
1123 Thread* self = Thread::Current();
1124 MutexLock mu(self, monitor_list_lock_);
1125 while (UNLIKELY(!allow_new_monitors_)) {
1126 monitor_add_condition_.WaitHoldingLocks(self);
1128 list_.push_front(m);
1131 void MonitorList::SweepMonitorList(IsMarkedCallback* callback, void* arg) {
1132 Thread* self = Thread::Current();
1133 MutexLock mu(self, monitor_list_lock_);
1134 for (auto it = list_.begin(); it != list_.end(); ) {
1136 // Disable the read barrier in GetObject() as this is called by GC.
1137 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
1138 // The object of a monitor can be null if we have deflated it.
1139 mirror::Object* new_obj = obj != nullptr ? callback(obj, arg) : nullptr;
1140 if (new_obj == nullptr) {
1141 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
1143 MonitorPool::ReleaseMonitor(self, m);
1144 it = list_.erase(it);
1146 m->SetObject(new_obj);
1152 struct MonitorDeflateArgs {
1153 MonitorDeflateArgs() : self(Thread::Current()), deflate_count(0) {}
1155 size_t deflate_count;
1158 static mirror::Object* MonitorDeflateCallback(mirror::Object* object, void* arg)
1159 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1160 MonitorDeflateArgs* args = reinterpret_cast<MonitorDeflateArgs*>(arg);
1161 if (Monitor::Deflate(args->self, object)) {
1162 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1163 ++args->deflate_count;
1164 // If we deflated, return nullptr so that the monitor gets removed from the array.
1167 return object; // Monitor was not deflated.
1170 size_t MonitorList::DeflateMonitors() {
1171 MonitorDeflateArgs args;
1172 Locks::mutator_lock_->AssertExclusiveHeld(args.self);
1173 SweepMonitorList(MonitorDeflateCallback, &args);
1174 return args.deflate_count;
1177 MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
1178 DCHECK(obj != nullptr);
1179 LockWord lock_word = obj->GetLockWord(true);
1180 switch (lock_word.GetState()) {
1181 case LockWord::kUnlocked:
1183 case LockWord::kForwardingAddress:
1185 case LockWord::kHashCode:
1187 case LockWord::kThinLocked:
1188 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1189 entry_count_ = 1 + lock_word.ThinLockCount();
1190 // Thin locks have no waiters.
1192 case LockWord::kFatLocked: {
1193 Monitor* mon = lock_word.FatLockMonitor();
1194 owner_ = mon->owner_;
1195 entry_count_ = 1 + mon->lock_count_;
1196 for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->GetWaitNext()) {
1197 waiters_.push_back(waiter);