blob: 269c97ed3b5068dd27e160dd639cb791be7edcf7 [file] [log] [blame]
Elliott Hughes88c5c352012-03-15 18:49:48 -07001/*
2 * Copyright (C) 2012 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 "scoped_thread_list_lock.h"
18
19#include "runtime.h"
20#include "thread_list.h"
21
22namespace art {
23
24ScopedThreadListLock::ScopedThreadListLock() {
25 // Avoid deadlock between two threads trying to SuspendAll
26 // simultaneously by going to kVmWait if the lock cannot be
27 // immediately acquired.
28 ThreadList* thread_list = Runtime::Current()->GetThreadList();
29 if (!thread_list->thread_list_lock_.TryLock()) {
30 Thread* self = Thread::Current();
31 if (self == NULL) {
32 // Self may be null during shutdown, but in that case there's no point going to kVmWait.
33 thread_list->thread_list_lock_.Lock();
34 } else {
Elliott Hughes34e06962012-04-09 13:55:55 -070035 ThreadState old_thread_state = self->SetState(kVmWait);
Elliott Hughes88c5c352012-03-15 18:49:48 -070036 thread_list->thread_list_lock_.Lock();
37 // If we have the lock, by definition there's no GC in progress (though we
38 // might be taking the lock in order to start one). We avoid the suspend
39 // check here so we don't risk going to sleep on the thread suspend count lock
40 // while holding the thread list lock.
41 self->SetStateWithoutSuspendCheck(old_thread_state);
42 }
43 }
44}
45
46ScopedThreadListLock::~ScopedThreadListLock() {
47 Runtime::Current()->GetThreadList()->thread_list_lock_.Unlock();
48}
49
50} // namespace art