OSDN Git Service

Merge "Use memory chunks for monitors on LP64"
[android-x86/art.git] / runtime / monitor.cc
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
38 namespace 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
67 bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
68 uint32_t Monitor::lock_profiling_threshold_ = 0;
69
70 bool Monitor::IsSensitiveThread() {
71   if (is_sensitive_thread_hook_ != NULL) {
72     return (*is_sensitive_thread_hook_)();
73   }
74   return false;
75 }
76
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;
80 }
81
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_),
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
104 Monitor::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
126 int32_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
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();
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()->CasLockWord(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
174 Monitor::~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  */
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) {
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  */
203 void 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
226 void Monitor::SetObject(mirror::Object* object) {
227   obj_ = object;
228 }
229
230 void 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
284 static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
285                                               __attribute__((format(printf, 1, 2)));
286
287 static 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
303 static 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
313 void 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
372 bool 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  */
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);
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
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()");
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
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()");
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
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) {
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  */
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;
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
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);
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       owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
685     }
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);
693       }
694       thread_list->Resume(owner, false);
695     }
696     self->SetMonitorEnterObject(nullptr);
697   }
698 }
699
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 {
703   return obj;
704 }
705
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 {
709   return obj;
710 }
711
712 mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
713   DCHECK(self != NULL);
714   DCHECK(obj != NULL);
715   obj = FakeLock(obj);
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));
720   while (true) {
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!
728         }
729         continue;  // Go again.
730       }
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!
740           } else {
741             // We'd overflow the recursion count, so inflate the monitor.
742             InflateThinLocked(self, h_obj, lock_word, 0);
743           }
744         } else {
745           // Contention.
746           contention_count++;
747           Runtime* runtime = Runtime::Current();
748           if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
749             NanoSleep(1000);  // Sleep for 1us and re-attempt.
750           } else {
751             contention_count = 0;
752             InflateThinLocked(self, h_obj, lock_word, 0);
753           }
754         }
755         continue;  // Start from the beginning.
756       }
757       case LockWord::kFatLocked: {
758         Monitor* mon = lock_word.FatLockMonitor();
759         mon->Lock(self);
760         return h_obj.Get();  // Success!
761       }
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.
766       default: {
767         LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
768         return h_obj.Get();
769       }
770     }
771   }
772 }
773
774 bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
775   DCHECK(self != NULL);
776   DCHECK(obj != 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:
783       // Fall-through.
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.
792         Thread* owner =
793             Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
794         FailedUnlock(h_obj.Get(), self, owner, nullptr);
795         return false;  // Failure.
796       } else {
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);
802         } else {
803           h_obj->SetLockWord(LockWord(), true);
804         }
805         return true;  // Success!
806       }
807     }
808     case LockWord::kFatLocked: {
809       Monitor* mon = lock_word.FatLockMonitor();
810       return mon->Unlock(self);
811     }
812     default: {
813       LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
814       return false;
815     }
816   }
817 }
818
819 /*
820  * Object.wait().  Also called for class init.
821  */
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:
829       // Fall-through.
830     case LockWord::kUnlocked:
831       ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
832       return;  // Failure.
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()");
838         return;  // Failure.
839       } else {
840         // We own the lock, inflate to enqueue ourself on the Monitor.
841         Inflate(self, self, obj, 0);
842         lock_word = obj->GetLockWord(true);
843       }
844       break;
845     }
846     case LockWord::kFatLocked:
847       break;  // Already set for a wait.
848     default: {
849       LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
850       return;
851     }
852   }
853   Monitor* mon = lock_word.FatLockMonitor();
854   mon->Wait(self, ms, ns, interruptShouldThrow, why);
855 }
856
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:
863       // Fall-through.
864     case LockWord::kUnlocked:
865       ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
866       return;  // Failure.
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()");
872         return;  // Failure.
873       } else {
874         // We own the lock but there's no Monitor and therefore no waiters.
875         return;  // Success.
876       }
877     }
878     case LockWord::kFatLocked: {
879       Monitor* mon = lock_word.FatLockMonitor();
880       if (notify_all) {
881         mon->NotifyAll(self);
882       } else {
883         mon->Notify(self);
884       }
885       return;  // Success.
886     }
887     default: {
888       LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
889       return;
890     }
891   }
892 }
893
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:
899       // Fall-through.
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();
907     }
908     default: {
909       LOG(FATAL) << "Unreachable";
910       return ThreadList::kInvalidThreadId;
911     }
912   }
913 }
914
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();
928     }
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();
934     }
935   }
936
937   if (wait_message != nullptr) {
938     if (pretty_object == nullptr) {
939       os << wait_message << "an unknown object";
940     } else {
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());
948       } else {
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());
952       }
953     }
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;
957     }
958     os << "\n";
959   }
960 }
961
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();
972     }
973   }
974   return result;
975 }
976
977 void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
978                          void* callback_context) {
979   mirror::ArtMethod* m = stack_visitor->GetMethod();
980   CHECK(m != NULL);
981
982   // Native methods are an easy special case.
983   // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
984   if (m->IsNative()) {
985     if (m->IsSynchronized()) {
986       mirror::Object* jni_this = stack_visitor->GetCurrentHandleScope()->GetReference(0);
987       callback(jni_this, callback_context);
988     }
989     return;
990   }
991
992   // Proxy methods should not be synchronized.
993   if (m->IsProxyMethod()) {
994     CHECK(!m->IsSynchronized());
995     return;
996   }
997
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.
1002   }
1003
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.
1009   }
1010
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()) {
1016     return;
1017   }
1018
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];
1024
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);
1029     }
1030
1031     uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
1032     mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
1033                                                                                  kReferenceVReg));
1034     callback(o, callback_context);
1035   }
1036 }
1037
1038 bool Monitor::IsValidLockWord(LockWord lock_word) {
1039   switch (lock_word.GetState()) {
1040     case LockWord::kUnlocked:
1041       // Nothing to check.
1042       return true;
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.
1054         }
1055       }
1056       return false;  // Fail - unowned monitor in an object.
1057     }
1058     case LockWord::kHashCode:
1059       return true;
1060     default:
1061       LOG(FATAL) << "Unreachable";
1062       return false;
1063   }
1064 }
1065
1066 bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1067   MutexLock mu(Thread::Current(), monitor_lock_);
1068   return owner_ != nullptr;
1069 }
1070
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) {
1075     *source_file = "";
1076     *line_number = 0;
1077     return;
1078   }
1079   *source_file = method->GetDeclaringClassSourceFile();
1080   if (*source_file == NULL) {
1081     *source_file = "";
1082   }
1083   *line_number = method->GetLineNumFromDexPC(dex_pc);
1084 }
1085
1086 uint32_t Monitor::GetOwnerThreadId() {
1087   MutexLock mu(Thread::Current(), monitor_lock_);
1088   Thread* owner = owner_;
1089   if (owner != NULL) {
1090     return owner->GetThreadId();
1091   } else {
1092     return ThreadList::kInvalidThreadId;
1093   }
1094 }
1095
1096 MonitorList::MonitorList()
1097     : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
1098       monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
1099 }
1100
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_);
1108 }
1109
1110 void MonitorList::DisallowNewMonitors() {
1111   MutexLock mu(Thread::Current(), monitor_list_lock_);
1112   allow_new_monitors_ = false;
1113 }
1114
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);
1120 }
1121
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);
1127   }
1128   list_.push_front(m);
1129 }
1130
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(); ) {
1135     Monitor* m = *it;
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 "
1142                     << obj;
1143       MonitorPool::ReleaseMonitor(self, m);
1144       it = list_.erase(it);
1145     } else {
1146       m->SetObject(new_obj);
1147       ++it;
1148     }
1149   }
1150 }
1151
1152 struct MonitorDeflateArgs {
1153   MonitorDeflateArgs() : self(Thread::Current()), deflate_count(0) {}
1154   Thread* const self;
1155   size_t deflate_count;
1156 };
1157
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.
1165     return nullptr;
1166   }
1167   return object;  // Monitor was not deflated.
1168 }
1169
1170 size_t MonitorList::DeflateMonitors() {
1171   MonitorDeflateArgs args;
1172   Locks::mutator_lock_->AssertExclusiveHeld(args.self);
1173   SweepMonitorList(MonitorDeflateCallback, &args);
1174   return args.deflate_count;
1175 }
1176
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:
1182       // Fall-through.
1183     case LockWord::kForwardingAddress:
1184       // Fall-through.
1185     case LockWord::kHashCode:
1186       break;
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.
1191       break;
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);
1198       }
1199       break;
1200     }
1201   }
1202 }
1203
1204 }  // namespace art