monitor_pool.h revision 44d6ff197b340b5ac2a4094db148b39c366317dd
1/*
2 * Copyright (C) 2014 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#ifndef ART_RUNTIME_MONITOR_POOL_H_
18#define ART_RUNTIME_MONITOR_POOL_H_
19
20#ifdef __LP64__
21#include <bitset>
22#include <stdint.h>
23
24#include "monitor.h"
25#include "runtime.h"
26#include "safe_map.h"
27#endif
28
29namespace art {
30
31// Abstraction to keep monitors small enough to fit in a lock word (32bits). On 32bit systems the
32// monitor id loses the alignment bits of the Monitor*.
33class MonitorPool {
34 public:
35  static MonitorPool* Create() {
36#ifndef __LP64__
37    return nullptr;
38#else
39    return new MonitorPool();
40#endif
41  }
42
43  static Monitor* MonitorFromMonitorId(MonitorId mon_id) {
44#ifndef __LP64__
45    return reinterpret_cast<Monitor*>(mon_id << 3);
46#else
47    return Runtime::Current()->GetMonitorPool()->LookupMonitorFromTable(mon_id);
48#endif
49  }
50
51  static MonitorId MonitorIdFromMonitor(Monitor* mon) {
52#ifndef __LP64__
53    return reinterpret_cast<MonitorId>(mon) >> 3;
54#else
55    return mon->GetMonitorId();
56#endif
57  }
58
59  static MonitorId CreateMonitorId(Thread* self, Monitor* mon) {
60#ifndef __LP64__
61    UNUSED(self);
62    return MonitorIdFromMonitor(mon);
63#else
64    return Runtime::Current()->GetMonitorPool()->AllocMonitorIdFromTable(self, mon);
65#endif
66  }
67
68  static void ReleaseMonitorId(MonitorId mon_id) {
69#ifndef __LP64__
70    UNUSED(mon_id);
71#else
72    Runtime::Current()->GetMonitorPool()->ReleaseMonitorIdFromTable(mon_id);
73#endif
74  }
75
76 private:
77#ifdef __LP64__
78  MonitorPool();
79
80  Monitor* LookupMonitorFromTable(MonitorId mon_id);
81
82  MonitorId LookupMonitorIdFromTable(Monitor* mon);
83
84  MonitorId AllocMonitorIdFromTable(Thread* self, Monitor* mon);
85
86  void ReleaseMonitorIdFromTable(MonitorId mon_id);
87
88  ReaderWriterMutex allocated_ids_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
89  static constexpr uint32_t kMaxMonitorId = 0xFFFF;
90  std::bitset<kMaxMonitorId> allocated_ids_ GUARDED_BY(allocated_ids_lock_);
91  SafeMap<MonitorId, Monitor*> table_ GUARDED_BY(allocated_ids_lock_);
92#endif
93};
94
95}  // namespace art
96
97#endif  // ART_RUNTIME_MONITOR_POOL_H_
98