monitor.cc revision 38c488bcd41ba632a646d7a1d790ec71a2fcf6fa
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
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
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
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.
15 */
16
17#include "monitor.h"
18
19#include <vector>
20
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"
33#include "thread.h"
34#include "thread_list.h"
35#include "verifier/method_verifier.h"
36#include "well_known_classes.h"
37
38namespace art {
39
40/*
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.
44 *
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.
48 *
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.
52 *
53 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
54 * in the LockWord value type.
55 *
56 * Monitors provide:
57 *  - mutually exclusive access to resources
58 *  - a way for multiple threads to wait for notification
59 *
60 * In effect, they fill the role of both mutexes and condition variables.
61 *
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
64 * at any given time.
65 */
66
67bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
68uint32_t Monitor::lock_profiling_threshold_ = 0;
69
70bool Monitor::IsSensitiveThread() {
71  if (is_sensitive_thread_hook_ != NULL) {
72    return (*is_sensitive_thread_hook_)();
73  }
74  return false;
75}
76
77void 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;
80}
81
82Monitor::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_),
85      num_waiters_(0),
86      owner_(owner),
87      lock_count_(0),
88      obj_(obj),
89      wait_set_(NULL),
90      hash_code_(hash_code),
91      locking_method_(NULL),
92      locking_dex_pc_(0),
93      monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
94#ifdef __LP64__
95  DCHECK(false) << "Should not be reached in 64b";
96  next_free_ = nullptr;
97#endif
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.
102}
103
104Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
105                 MonitorId id)
106    : monitor_lock_("a monitor lock", kMonitorLock),
107      monitor_contenders_("monitor contenders", monitor_lock_),
108      num_waiters_(0),
109      owner_(owner),
110      lock_count_(0),
111      obj_(obj),
112      wait_set_(NULL),
113      hash_code_(hash_code),
114      locking_method_(NULL),
115      locking_dex_pc_(0),
116      monitor_id_(id) {
117#ifdef __LP64__
118  next_free_ = nullptr;
119#endif
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.
124}
125
126int32_t Monitor::GetHashCode() {
127  while (!HasHashCode()) {
128    if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
129      break;
130    }
131  }
132  DCHECK(HasHashCode());
133  return hash_code_.LoadRelaxed();
134}
135
136bool 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();
145      break;
146    }
147    case LockWord::kHashCode: {
148      CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
149      break;
150    }
151    case LockWord::kFatLocked: {
152      // The owner_ is suspended but another thread beat us to install a monitor.
153      return false;
154    }
155    case LockWord::kUnlocked: {
156      LOG(FATAL) << "Inflating unlocked lock word";
157      break;
158    }
159    default: {
160      LOG(FATAL) << "Invalid monitor state " << lw.GetState();
161      return false;
162    }
163  }
164  LockWord fat(this);
165  // Publish the updated lock word, which may race with other threads.
166  bool success = GetObject()->CasLockWordWeakSequentiallyConsistent(lw, fat);
167  // Lock profiling.
168  if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
169    locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_);
170  }
171  return success;
172}
173
174Monitor::~Monitor() {
175  // Deflated monitors have a null object.
176}
177
178/*
179 * Links a thread into a monitor's wait set.  The monitor lock must be
180 * held by the caller of this routine.
181 */
182void 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) {
187    wait_set_ = thread;
188    return;
189  }
190
191  // push_back.
192  Thread* t = wait_set_;
193  while (t->GetWaitNext() != nullptr) {
194    t = t->GetWaitNext();
195  }
196  t->SetWaitNext(thread);
197}
198
199/*
200 * Unlinks a thread from a monitor's wait set.  The monitor lock must
201 * be held by the caller of this routine.
202 */
203void Monitor::RemoveFromWaitSet(Thread *thread) {
204  DCHECK(owner_ == Thread::Current());
205  DCHECK(thread != NULL);
206  if (wait_set_ == NULL) {
207    return;
208  }
209  if (wait_set_ == thread) {
210    wait_set_ = thread->GetWaitNext();
211    thread->SetWaitNext(nullptr);
212    return;
213  }
214
215  Thread* t = wait_set_;
216  while (t->GetWaitNext() != NULL) {
217    if (t->GetWaitNext() == thread) {
218      t->SetWaitNext(thread->GetWaitNext());
219      thread->SetWaitNext(nullptr);
220      return;
221    }
222    t = t->GetWaitNext();
223  }
224}
225
226void Monitor::SetObject(mirror::Object* object) {
227  obj_ = object;
228}
229
230void Monitor::Lock(Thread* self) {
231  MutexLock mu(self, monitor_lock_);
232  while (true) {
233    if (owner_ == nullptr) {  // Unowned.
234      owner_ = self;
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_);
240      }
241      return;
242    } else if (owner_ == self) {  // Recursive.
243      lock_count_++;
244      return;
245    }
246    // Contended.
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.
252    ++num_waiters_;
253    monitor_lock_.Unlock(self);  // Let go of locks in order.
254    self->SetMonitorEnterObject(GetObject());
255    {
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;
266          } else {
267            sample_percent = 100 * wait_ms / lock_profiling_threshold_;
268          }
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);
274          }
275        }
276      }
277    }
278    self->SetMonitorEnterObject(nullptr);
279    monitor_lock_.Lock(self);  // Reacquire locks in order.
280    --num_waiters_;
281  }
282}
283
284static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
285                                              __attribute__((format(printf, 1, 2)));
286
287static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
288    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
289  va_list args;
290  va_start(args, fmt);
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;
296    self->Dump(ss);
297    LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
298        << self->GetException(NULL)->Dump() << "\n" << ss.str();
299  }
300  va_end(args);
301}
302
303static std::string ThreadToString(Thread* thread) {
304  if (thread == NULL) {
305    return "NULL";
306  }
307  std::ostringstream oss;
308  // TODO: alternatively, we could just return the thread's name.
309  oss << *thread;
310  return oss.str();
311}
312
313void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
314                           Monitor* monitor) {
315  Thread* current_owner = NULL;
316  std::string current_owner_string;
317  std::string expected_owner_string;
318  std::string found_owner_string;
319  {
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);
329  }
330  if (current_owner == NULL) {
331    if (found_owner == NULL) {
332      ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
333                                         " on thread '%s'",
334                                         PrettyTypeOf(o).c_str(),
335                                         expected_owner_string.c_str());
336    } else {
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());
343    }
344  } else {
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());
352    } else {
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());
361      } else {
362        ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
363                                           " on thread '%s",
364                                           current_owner_string.c_str(),
365                                           PrettyTypeOf(o).c_str(),
366                                           expected_owner_string.c_str());
367      }
368    }
369  }
370}
371
372bool Monitor::Unlock(Thread* self) {
373  DCHECK(self != NULL);
374  MutexLock mu(self, monitor_lock_);
375  Thread* owner = owner_;
376  if (owner == self) {
377    // We own the monitor, so nobody else can be in here.
378    if (lock_count_ == 0) {
379      owner_ = NULL;
380      locking_method_ = NULL;
381      locking_dex_pc_ = 0;
382      // Wake a contender.
383      monitor_contenders_.Signal(self);
384    } else {
385      --lock_count_;
386    }
387  } else {
388    // We don't own this, so we're not allowed to unlock it.
389    // The JNI spec says that we should throw IllegalMonitorStateException
390    // in this case.
391    FailedUnlock(GetObject(), self, owner, this);
392    return false;
393  }
394  return true;
395}
396
397/*
398 * Wait on a monitor until timeout, interrupt, or notification.  Used for
399 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
400 *
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.
407 *
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.
411 *
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.
416 *
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.
419 */
420void 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);
424
425  monitor_lock_.Lock(self);
426
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()");
431    return;
432  }
433
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)) {
437    why = kWaiting;
438  }
439
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);
446    return;
447  }
448
449  /*
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.
453   *
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.
458   */
459  AppendToWaitSet(self);
460  ++num_waiters_;
461  int prev_lock_count = lock_count_;
462  lock_count_ = 0;
463  owner_ = NULL;
464  mirror::ArtMethod* saved_method = locking_method_;
465  locking_method_ = NULL;
466  uintptr_t saved_dex_pc = locking_dex_pc_;
467  locking_dex_pc_ = 0;
468
469  /*
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.
473   */
474  self->TransitionFromRunnableToSuspended(why);
475
476  bool was_interrupted = false;
477  {
478    // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
479    MutexLock mu(self, *self->GetWaitMutex());
480
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
483    // up.
484    DCHECK(self->GetWaitMonitor() == nullptr);
485    self->SetWaitMonitor(this);
486
487    // Release the monitor lock.
488    monitor_contenders_.Signal(self);
489    monitor_lock_.Unlock(self);
490
491    // Handle the case where the thread was interrupted before we called wait().
492    if (self->IsInterruptedLocked()) {
493      was_interrupted = true;
494    } else {
495      // Wait for a notification or a timeout to occur.
496      if (why == kWaiting) {
497        self->GetWaitConditionVariable()->Wait(self);
498      } else {
499        DCHECK(why == kTimedWaiting || why == kSleeping) << why;
500        self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
501      }
502      if (self->IsInterruptedLocked()) {
503        was_interrupted = true;
504      }
505      self->SetInterruptedLocked(false);
506    }
507  }
508
509  // Set self->status back to kRunnable, and self-suspend if needed.
510  self->TransitionFromSuspendedToRunnable();
511
512  {
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);
520  }
521
522  // Re-acquire the monitor and lock.
523  Lock(self);
524  monitor_lock_.Lock(self);
525  self->GetWaitMutex()->AssertNotHeld(self);
526
527  /*
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.
532   */
533  owner_ = self;
534  lock_count_ = prev_lock_count;
535  locking_method_ = saved_method;
536  locking_dex_pc_ = saved_dex_pc;
537  --num_waiters_;
538  RemoveFromWaitSet(self);
539
540  monitor_lock_.Unlock(self);
541
542  if (was_interrupted) {
543    /*
544     * We were interrupted while waiting, or somebody interrupted an
545     * un-interruptible thread earlier and we're bailing out immediately.
546     *
547     * The doc sayeth: "The interrupted status of the current thread is
548     * cleared when this exception is thrown."
549     */
550    {
551      MutexLock mu(self, *self->GetWaitMutex());
552      self->SetInterruptedLocked(false);
553    }
554    if (interruptShouldThrow) {
555      ThrowLocation throw_location = self->GetCurrentLocationForThrow();
556      self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
557    }
558  }
559}
560
561void 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()");
567    return;
568  }
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);
574
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);
579      return;
580    }
581  }
582}
583
584void 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()");
590    return;
591  }
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);
597    thread->Notify();
598  }
599}
600
601bool 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) {
612      return false;
613    }
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()) {
618        return false;
619      }
620      // Can't deflate if our lock count is too high.
621      if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
622        return false;
623      }
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();
631    } else {
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";
635    }
636    // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
637    // next GC.
638    monitor->obj_ = nullptr;
639  }
640  return true;
641}
642
643/*
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.
647 */
648void 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;
658    } else {
659      VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
660          << " created monitor " << m << " for object " << obj;
661    }
662    Runtime::Current()->GetMonitorList()->Add(m);
663    CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
664  } else {
665    MonitorPool::ReleaseMonitor(self, m);
666  }
667}
668
669void 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);
676  } else {
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());
680    bool timed_out;
681    Thread* owner;
682    {
683      ScopedThreadStateChange tsc(self, kBlocked);
684      // Take suspend thread lock to avoid races with threads trying to suspend this one.
685      MutexLock mu(self, *Locks::thread_list_suspend_thread_lock_);
686      owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
687    }
688    if (owner != nullptr) {
689      // We succeeded in suspending the thread, check the lock's status didn't change.
690      lock_word = obj->GetLockWord(true);
691      if (lock_word.GetState() == LockWord::kThinLocked &&
692          lock_word.ThinLockOwner() == owner_thread_id) {
693        // Go ahead and inflate the lock.
694        Inflate(self, owner, obj.Get(), hash_code);
695      }
696      thread_list->Resume(owner, false);
697    }
698    self->SetMonitorEnterObject(nullptr);
699  }
700}
701
702// Fool annotalysis into thinking that the lock on obj is acquired.
703static mirror::Object* FakeLock(mirror::Object* obj)
704    EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
705  return obj;
706}
707
708// Fool annotalysis into thinking that the lock on obj is release.
709static mirror::Object* FakeUnlock(mirror::Object* obj)
710    UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
711  return obj;
712}
713
714mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
715  DCHECK(self != NULL);
716  DCHECK(obj != NULL);
717  obj = FakeLock(obj);
718  uint32_t thread_id = self->GetThreadId();
719  size_t contention_count = 0;
720  StackHandleScope<1> hs(self);
721  Handle<mirror::Object> h_obj(hs.NewHandle(obj));
722  while (true) {
723    LockWord lock_word = h_obj->GetLockWord(true);
724    switch (lock_word.GetState()) {
725      case LockWord::kUnlocked: {
726        LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
727        if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
728          // CasLockWord enforces more than the acquire ordering we need here.
729          return h_obj.Get();  // Success!
730        }
731        continue;  // Go again.
732      }
733      case LockWord::kThinLocked: {
734        uint32_t owner_thread_id = lock_word.ThinLockOwner();
735        if (owner_thread_id == thread_id) {
736          // We own the lock, increase the recursion count.
737          uint32_t new_count = lock_word.ThinLockCount() + 1;
738          if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
739            LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
740            h_obj->SetLockWord(thin_locked, true);
741            return h_obj.Get();  // Success!
742          } else {
743            // We'd overflow the recursion count, so inflate the monitor.
744            InflateThinLocked(self, h_obj, lock_word, 0);
745          }
746        } else {
747          // Contention.
748          contention_count++;
749          Runtime* runtime = Runtime::Current();
750          if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
751            // TODO: Consider switching the thread state to kBlocked when we are yielding.
752            // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
753            // parameter you pass in. This can cause thread suspension to take excessively long
754            // and make long pauses. See b/16307460.
755            sched_yield();
756          } else {
757            contention_count = 0;
758            InflateThinLocked(self, h_obj, lock_word, 0);
759          }
760        }
761        continue;  // Start from the beginning.
762      }
763      case LockWord::kFatLocked: {
764        Monitor* mon = lock_word.FatLockMonitor();
765        mon->Lock(self);
766        return h_obj.Get();  // Success!
767      }
768      case LockWord::kHashCode:
769        // Inflate with the existing hashcode.
770        Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
771        continue;  // Start from the beginning.
772      default: {
773        LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
774        return h_obj.Get();
775      }
776    }
777  }
778}
779
780bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
781  DCHECK(self != NULL);
782  DCHECK(obj != NULL);
783  obj = FakeUnlock(obj);
784  LockWord lock_word = obj->GetLockWord(true);
785  StackHandleScope<1> hs(self);
786  Handle<mirror::Object> h_obj(hs.NewHandle(obj));
787  switch (lock_word.GetState()) {
788    case LockWord::kHashCode:
789      // Fall-through.
790    case LockWord::kUnlocked:
791      FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
792      return false;  // Failure.
793    case LockWord::kThinLocked: {
794      uint32_t thread_id = self->GetThreadId();
795      uint32_t owner_thread_id = lock_word.ThinLockOwner();
796      if (owner_thread_id != thread_id) {
797        // TODO: there's a race here with the owner dying while we unlock.
798        Thread* owner =
799            Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
800        FailedUnlock(h_obj.Get(), self, owner, nullptr);
801        return false;  // Failure.
802      } else {
803        // We own the lock, decrease the recursion count.
804        if (lock_word.ThinLockCount() != 0) {
805          uint32_t new_count = lock_word.ThinLockCount() - 1;
806          LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
807          h_obj->SetLockWord(thin_locked, true);
808        } else {
809          h_obj->SetLockWord(LockWord(), true);
810        }
811        return true;  // Success!
812      }
813    }
814    case LockWord::kFatLocked: {
815      Monitor* mon = lock_word.FatLockMonitor();
816      return mon->Unlock(self);
817    }
818    default: {
819      LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
820      return false;
821    }
822  }
823}
824
825/*
826 * Object.wait().  Also called for class init.
827 */
828void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
829                   bool interruptShouldThrow, ThreadState why) {
830  DCHECK(self != nullptr);
831  DCHECK(obj != nullptr);
832  LockWord lock_word = obj->GetLockWord(true);
833  switch (lock_word.GetState()) {
834    case LockWord::kHashCode:
835      // Fall-through.
836    case LockWord::kUnlocked:
837      ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
838      return;  // Failure.
839    case LockWord::kThinLocked: {
840      uint32_t thread_id = self->GetThreadId();
841      uint32_t owner_thread_id = lock_word.ThinLockOwner();
842      if (owner_thread_id != thread_id) {
843        ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
844        return;  // Failure.
845      } else {
846        // We own the lock, inflate to enqueue ourself on the Monitor.
847        Inflate(self, self, obj, 0);
848        lock_word = obj->GetLockWord(true);
849      }
850      break;
851    }
852    case LockWord::kFatLocked:
853      break;  // Already set for a wait.
854    default: {
855      LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
856      return;
857    }
858  }
859  Monitor* mon = lock_word.FatLockMonitor();
860  mon->Wait(self, ms, ns, interruptShouldThrow, why);
861}
862
863void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
864  DCHECK(self != nullptr);
865  DCHECK(obj != nullptr);
866  LockWord lock_word = obj->GetLockWord(true);
867  switch (lock_word.GetState()) {
868    case LockWord::kHashCode:
869      // Fall-through.
870    case LockWord::kUnlocked:
871      ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
872      return;  // Failure.
873    case LockWord::kThinLocked: {
874      uint32_t thread_id = self->GetThreadId();
875      uint32_t owner_thread_id = lock_word.ThinLockOwner();
876      if (owner_thread_id != thread_id) {
877        ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
878        return;  // Failure.
879      } else {
880        // We own the lock but there's no Monitor and therefore no waiters.
881        return;  // Success.
882      }
883    }
884    case LockWord::kFatLocked: {
885      Monitor* mon = lock_word.FatLockMonitor();
886      if (notify_all) {
887        mon->NotifyAll(self);
888      } else {
889        mon->Notify(self);
890      }
891      return;  // Success.
892    }
893    default: {
894      LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
895      return;
896    }
897  }
898}
899
900uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
901  DCHECK(obj != nullptr);
902  LockWord lock_word = obj->GetLockWord(true);
903  switch (lock_word.GetState()) {
904    case LockWord::kHashCode:
905      // Fall-through.
906    case LockWord::kUnlocked:
907      return ThreadList::kInvalidThreadId;
908    case LockWord::kThinLocked:
909      return lock_word.ThinLockOwner();
910    case LockWord::kFatLocked: {
911      Monitor* mon = lock_word.FatLockMonitor();
912      return mon->GetOwnerThreadId();
913    }
914    default: {
915      LOG(FATAL) << "Unreachable";
916      return ThreadList::kInvalidThreadId;
917    }
918  }
919}
920
921void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
922  // Determine the wait message and object we're waiting or blocked upon.
923  mirror::Object* pretty_object = nullptr;
924  const char* wait_message = nullptr;
925  uint32_t lock_owner = ThreadList::kInvalidThreadId;
926  ThreadState state = thread->GetState();
927  if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
928    wait_message = (state == kSleeping) ? "  - sleeping on " : "  - waiting on ";
929    Thread* self = Thread::Current();
930    MutexLock mu(self, *thread->GetWaitMutex());
931    Monitor* monitor = thread->GetWaitMonitor();
932    if (monitor != nullptr) {
933      pretty_object = monitor->GetObject();
934    }
935  } else if (state == kBlocked) {
936    wait_message = "  - waiting to lock ";
937    pretty_object = thread->GetMonitorEnterObject();
938    if (pretty_object != nullptr) {
939      lock_owner = pretty_object->GetLockOwnerThreadId();
940    }
941  }
942
943  if (wait_message != nullptr) {
944    if (pretty_object == nullptr) {
945      os << wait_message << "an unknown object";
946    } else {
947      if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
948          Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
949        // Getting the identity hashcode here would result in lock inflation and suspension of the
950        // current thread, which isn't safe if this is the only runnable thread.
951        os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
952                                           reinterpret_cast<intptr_t>(pretty_object),
953                                           PrettyTypeOf(pretty_object).c_str());
954      } else {
955        // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
956        os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
957                                           PrettyTypeOf(pretty_object).c_str());
958      }
959    }
960    // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
961    if (lock_owner != ThreadList::kInvalidThreadId) {
962      os << " held by thread " << lock_owner;
963    }
964    os << "\n";
965  }
966}
967
968mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
969  // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
970  // definition of contended that includes a monitor a thread is trying to enter...
971  mirror::Object* result = thread->GetMonitorEnterObject();
972  if (result == NULL) {
973    // ...but also a monitor that the thread is waiting on.
974    MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
975    Monitor* monitor = thread->GetWaitMonitor();
976    if (monitor != NULL) {
977      result = monitor->GetObject();
978    }
979  }
980  return result;
981}
982
983void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
984                         void* callback_context) {
985  mirror::ArtMethod* m = stack_visitor->GetMethod();
986  CHECK(m != NULL);
987
988  // Native methods are an easy special case.
989  // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
990  if (m->IsNative()) {
991    if (m->IsSynchronized()) {
992      mirror::Object* jni_this = stack_visitor->GetCurrentHandleScope()->GetReference(0);
993      callback(jni_this, callback_context);
994    }
995    return;
996  }
997
998  // Proxy methods should not be synchronized.
999  if (m->IsProxyMethod()) {
1000    CHECK(!m->IsSynchronized());
1001    return;
1002  }
1003
1004  // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
1005  if (m->IsClassInitializer()) {
1006    callback(m->GetDeclaringClass(), callback_context);
1007    // Fall through because there might be synchronization in the user code too.
1008  }
1009
1010  // Is there any reason to believe there's any synchronization in this method?
1011  const DexFile::CodeItem* code_item = m->GetCodeItem();
1012  CHECK(code_item != NULL) << PrettyMethod(m);
1013  if (code_item->tries_size_ == 0) {
1014    return;  // No "tries" implies no synchronization, so no held locks to report.
1015  }
1016
1017  // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1018  // the locks held in this stack frame.
1019  std::vector<uint32_t> monitor_enter_dex_pcs;
1020  verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), &monitor_enter_dex_pcs);
1021  if (monitor_enter_dex_pcs.empty()) {
1022    return;
1023  }
1024
1025  for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
1026    // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1027    // We want the registers used by those instructions (so we can read the values out of them).
1028    uint32_t dex_pc = monitor_enter_dex_pcs[i];
1029    uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
1030
1031    // Quick sanity check.
1032    if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
1033      LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
1034                 << reinterpret_cast<void*>(monitor_enter_instruction);
1035    }
1036
1037    uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
1038    mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
1039                                                                                 kReferenceVReg));
1040    callback(o, callback_context);
1041  }
1042}
1043
1044bool Monitor::IsValidLockWord(LockWord lock_word) {
1045  switch (lock_word.GetState()) {
1046    case LockWord::kUnlocked:
1047      // Nothing to check.
1048      return true;
1049    case LockWord::kThinLocked:
1050      // Basic sanity check of owner.
1051      return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1052    case LockWord::kFatLocked: {
1053      // Check the  monitor appears in the monitor list.
1054      Monitor* mon = lock_word.FatLockMonitor();
1055      MonitorList* list = Runtime::Current()->GetMonitorList();
1056      MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1057      for (Monitor* list_mon : list->list_) {
1058        if (mon == list_mon) {
1059          return true;  // Found our monitor.
1060        }
1061      }
1062      return false;  // Fail - unowned monitor in an object.
1063    }
1064    case LockWord::kHashCode:
1065      return true;
1066    default:
1067      LOG(FATAL) << "Unreachable";
1068      return false;
1069  }
1070}
1071
1072bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1073  MutexLock mu(Thread::Current(), monitor_lock_);
1074  return owner_ != nullptr;
1075}
1076
1077void Monitor::TranslateLocation(mirror::ArtMethod* method, uint32_t dex_pc,
1078                                const char** source_file, uint32_t* line_number) const {
1079  // If method is null, location is unknown
1080  if (method == NULL) {
1081    *source_file = "";
1082    *line_number = 0;
1083    return;
1084  }
1085  *source_file = method->GetDeclaringClassSourceFile();
1086  if (*source_file == NULL) {
1087    *source_file = "";
1088  }
1089  *line_number = method->GetLineNumFromDexPC(dex_pc);
1090}
1091
1092uint32_t Monitor::GetOwnerThreadId() {
1093  MutexLock mu(Thread::Current(), monitor_lock_);
1094  Thread* owner = owner_;
1095  if (owner != NULL) {
1096    return owner->GetThreadId();
1097  } else {
1098    return ThreadList::kInvalidThreadId;
1099  }
1100}
1101
1102MonitorList::MonitorList()
1103    : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
1104      monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
1105}
1106
1107MonitorList::~MonitorList() {
1108  Thread* self = Thread::Current();
1109  MutexLock mu(self, monitor_list_lock_);
1110  // Release all monitors to the pool.
1111  // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1112  // clear faster in the pool.
1113  MonitorPool::ReleaseMonitors(self, &list_);
1114}
1115
1116void MonitorList::DisallowNewMonitors() {
1117  MutexLock mu(Thread::Current(), monitor_list_lock_);
1118  allow_new_monitors_ = false;
1119}
1120
1121void MonitorList::AllowNewMonitors() {
1122  Thread* self = Thread::Current();
1123  MutexLock mu(self, monitor_list_lock_);
1124  allow_new_monitors_ = true;
1125  monitor_add_condition_.Broadcast(self);
1126}
1127
1128void MonitorList::Add(Monitor* m) {
1129  Thread* self = Thread::Current();
1130  MutexLock mu(self, monitor_list_lock_);
1131  while (UNLIKELY(!allow_new_monitors_)) {
1132    monitor_add_condition_.WaitHoldingLocks(self);
1133  }
1134  list_.push_front(m);
1135}
1136
1137void MonitorList::SweepMonitorList(IsMarkedCallback* callback, void* arg) {
1138  Thread* self = Thread::Current();
1139  MutexLock mu(self, monitor_list_lock_);
1140  for (auto it = list_.begin(); it != list_.end(); ) {
1141    Monitor* m = *it;
1142    // Disable the read barrier in GetObject() as this is called by GC.
1143    mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
1144    // The object of a monitor can be null if we have deflated it.
1145    mirror::Object* new_obj = obj != nullptr ? callback(obj, arg) : nullptr;
1146    if (new_obj == nullptr) {
1147      VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
1148                    << obj;
1149      MonitorPool::ReleaseMonitor(self, m);
1150      it = list_.erase(it);
1151    } else {
1152      m->SetObject(new_obj);
1153      ++it;
1154    }
1155  }
1156}
1157
1158struct MonitorDeflateArgs {
1159  MonitorDeflateArgs() : self(Thread::Current()), deflate_count(0) {}
1160  Thread* const self;
1161  size_t deflate_count;
1162};
1163
1164static mirror::Object* MonitorDeflateCallback(mirror::Object* object, void* arg)
1165    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1166  MonitorDeflateArgs* args = reinterpret_cast<MonitorDeflateArgs*>(arg);
1167  if (Monitor::Deflate(args->self, object)) {
1168    DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1169    ++args->deflate_count;
1170    // If we deflated, return nullptr so that the monitor gets removed from the array.
1171    return nullptr;
1172  }
1173  return object;  // Monitor was not deflated.
1174}
1175
1176size_t MonitorList::DeflateMonitors() {
1177  MonitorDeflateArgs args;
1178  Locks::mutator_lock_->AssertExclusiveHeld(args.self);
1179  SweepMonitorList(MonitorDeflateCallback, &args);
1180  return args.deflate_count;
1181}
1182
1183MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
1184  DCHECK(obj != nullptr);
1185  LockWord lock_word = obj->GetLockWord(true);
1186  switch (lock_word.GetState()) {
1187    case LockWord::kUnlocked:
1188      // Fall-through.
1189    case LockWord::kForwardingAddress:
1190      // Fall-through.
1191    case LockWord::kHashCode:
1192      break;
1193    case LockWord::kThinLocked:
1194      owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1195      entry_count_ = 1 + lock_word.ThinLockCount();
1196      // Thin locks have no waiters.
1197      break;
1198    case LockWord::kFatLocked: {
1199      Monitor* mon = lock_word.FatLockMonitor();
1200      owner_ = mon->owner_;
1201      entry_count_ = 1 + mon->lock_count_;
1202      for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->GetWaitNext()) {
1203        waiters_.push_back(waiter);
1204      }
1205      break;
1206    }
1207  }
1208}
1209
1210}  // namespace art
1211