Skip to content

Commit 2cb821d

Browse files
authored
perf(runtime): drop three emulated thread_locals from hot paths (#2137)
### Description The runtime's minSdk is below 29, so every `thread_local` it declares is emulated: each access is a call to `__emutls_get_address`, and a `thread_local` with a destructor also has to look up `__tls_guard` (or its own init guard) first. This PR removes three of them from hot paths. In each case only one thread touches the data: the thread holding the isolate's `Locker`, or the event loop's home thread. So it can live on the object instead. 1. **`MethodCache`'s signature key** (`static thread_local std::string s_signatureKey`) becomes a per-`Runtime` scratch string, reached through `Runtime::GetRuntime(args.GetIsolate())->GetSignatureKeyScratch()`. On a cache hit, `ResolveMethodSignature` and `ResolveConstructorSignature` each made three `__emutls_get_address` calls: guard, string, guard. That cost was paid on every overload-resolved JS→Java call and every Java construction from JS (e.g. `new java.lang.Object()`). The key is still copied before resolving, because resolving calls into Java, which can call back into JS and reuse the scratch. 2. **`SetDefaultOverrides`' field cache** (a function-local `thread_local robin_hood::unordered_map<jclass, jfieldID>`) moves onto the `Runtime`. This removes two lookups (the map and its init guard) from every construction of an implementation with default-method overrides, plus the per-thread TLS destructor registration. 3. **`EventLoop`'s looper callback depth** (`thread_local int t_looperCallbackDepth`) becomes an `EventLoop` member. This removes one lookup per eventfd/timerfd callback. The fd callbacks already receive the `EventLoop` as their data pointer and only run on its home thread. As a result, `IsInLooperCallback()` changes from a static to an instance method that answers for that loop's home thread. It has no callers today. Why a per-`Runtime` value is safe: a runtime's JS, and so `MethodCache` and `RegisterInstance`, only runs on the thread holding its isolate's `Locker`, so two threads never share the scratch at once. Same-thread re-entry (Java calling back into JS mid-resolve) is handled by the copy noted in (1). Same-thread re-entry already existed with the `thread_local`. #### Emulated-TLS call sites `bl __emutls_get_address` sites per control variable in the linked, unstripped arm64-v8a `libNativeScript.so` (`:runtime:externalNativeBuildRelease`, RelWithDebInfo, NDK 27.3): | variable | before | after | |---|---:|---:| | `MethodCache` `s_signatureKey` | 8 | 0 | | `__tls_guard` (all) | 14 | 2 (V8's) | | `SetDefaultOverrides` map + its init guard | 4 | 0 | | `EventLoop` `t_looperCallbackDepth` | 2 | 0 | | whole library, all variables | 1627 | 1595 | The four rows account for 26 of the 32 removed sites. The other 6 come from code-generation and inlining differences elsewhere in the library, which were not attributed to a variable. In the three changed objects (`MethodCache.cpp.o`, `CallbackHandlers.cpp.o`, `EventLoop.cpp.o`), the relocations go from 68 to 41 calls. That is 27 rather than 26 because one `t_looperCallbackDepth` site was in `IsInLooperCallback()`, which has no callers and is dropped at link. The only emutls variables left in those objects are `JEnv::s_thread` and, in `EventLoop.cpp.o`, `t_pumpDepth`. No benchmark numbers: each removed lookup is a few ns, and the counts above are the claim. ### Testing Full suite (`runtestsAndVerifyResults`) on an arm64 API 36.1 emulator: 1773 specs, 0 failures. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Callback tracking and cached runtime data are now scoped to individual runtime instances, improving consistency when multiple runtimes are active. * Callback status checks now report whether the specific event loop is running a callback on its home thread. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 9c4895a commit 2cb821d

5 files changed

Lines changed: 46 additions & 28 deletions

File tree

‎test-app/runtime/src/main/cpp/CallbackHandlers.cpp‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -151,8 +151,8 @@ namespace {
151151
* app has one, lacks the field and keeps its own behaviour. The class cache hands out one
152152
* global reference per class name for the life of the process, so it is a stable key.
153153
*/
154-
void SetDefaultOverrides(JNIEnv* env, jobject instance, jclass clazz, uint64_t defaultOverrides) {
155-
thread_local robin_hood::unordered_map<jclass, jfieldID> fields;
154+
void SetDefaultOverrides(Runtime* runtime, JNIEnv* env, jobject instance, jclass clazz, uint64_t defaultOverrides) {
155+
auto& fields = runtime->GetDefaultOverridesFields();
156156

157157
jfieldID field;
158158
auto found = fields.find(clazz);
@@ -270,7 +270,7 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local<Object> &j
270270
// Before any Java code but the constructor's own can see the instance.
271271
// An interface proxy's handler received the mask with the instance.
272272
if (defaultOverrides != 0 && instance != nullptr && !mi.isInterfaceProxy) {
273-
SetDefaultOverrides(env, instance, generatedJavaClass, defaultOverrides);
273+
SetDefaultOverrides(runtime, env, instance, generatedJavaClass, defaultOverrides);
274274
}
275275

276276
jlong usedJavaMemory = env.CallLongMethod(runtime->GetJavaRuntime(), REGISTER_CONSTRUCTED_INSTANCE_ID,

‎test-app/runtime/src/main/cpp/EventLoop.cpp‎

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -792,18 +792,13 @@ EventLoop::PumpResult EventLoop::PumpUntil(double deadlineSeconds,
792792
}
793793

794794
namespace {
795-
// Depth, not a flag: an fd callback can dispatch JS that lands back in
796-
// another callback through a nested drain.
797-
thread_local int t_looperCallbackDepth = 0;
798-
799795
struct LooperCallbackScope {
800-
LooperCallbackScope() { ++t_looperCallbackDepth; }
801-
~LooperCallbackScope() { --t_looperCallbackDepth; }
796+
explicit LooperCallbackScope(int& depth) : depth_(depth) { ++depth_; }
797+
~LooperCallbackScope() { --depth_; }
798+
int& depth_;
802799
};
803800
} // namespace
804801

805-
bool EventLoop::IsInLooperCallback() { return t_looperCallbackDepth > 0; }
806-
807802
void EventLoop::WaitForInternalWork(int timeoutMs, bool pumpDeliverable) {
808803
const DrainFilter filter =
809804
pumpDeliverable ? DrainFilter::kPumpDeliverable : DrainFilter::kNestableV8;
@@ -853,7 +848,7 @@ void EventLoop::WaitForInternalWork(int timeoutMs, bool pumpDeliverable) {
853848
}
854849

855850
int EventLoop::EventFdCallback(int fd, int events, void* data) {
856-
LooperCallbackScope callbackScope;
851+
LooperCallbackScope callbackScope(static_cast<EventLoop*>(data)->looperCallbackDepth_);
857852
uint64_t value;
858853
// EFD_SEMAPHORE: consumes exactly one unit; while more remain the fd stays
859854
// readable and ALooper calls back next poll, interleaving with Java
@@ -867,7 +862,7 @@ int EventLoop::EventFdCallback(int fd, int events, void* data) {
867862
}
868863

869864
int EventLoop::TimerFdCallback(int fd, int events, void* data) {
870-
LooperCallbackScope callbackScope;
865+
LooperCallbackScope callbackScope(static_cast<EventLoop*>(data)->looperCallbackDepth_);
871866
uint64_t expirations;
872867
if (read(fd, &expirations, sizeof(expirations)) != sizeof(expirations)) {
873868
return 1;

‎test-app/runtime/src/main/cpp/EventLoop.h‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -191,15 +191,15 @@ class EventLoop {
191191
void RunNestableV8Tasks();
192192

193193
/**
194-
* True while the calling thread is inside one of this process's ALooper
195-
* fd callbacks. Android's Looper::pollInner holds a Response& into its
196-
* response vector across each callback; a nested ALooper_pollOnce on the
197-
* same looper clears and reallocates that vector, so the outer poll
198-
* resumes over freed memory. Any code that pumps the looper (module
194+
* True while this loop's home thread is inside one of the loop's ALooper
195+
* fd callbacks; ask it only from the home thread. Android's
196+
* Looper::pollInner holds a Response& into its response vector across
197+
* each callback; a nested ALooper_pollOnce on the same looper clears and
198+
* reallocates that vector, so the outer poll resumes over freed memory. Any code that pumps the looper (module
199199
* evaluation, the boot backstop, the fetch yield) must consult this and
200200
* drain queues directly instead of polling when it is set.
201201
*/
202-
static bool IsInLooperCallback();
202+
bool IsInLooperCallback() const { return looperCallbackDepth_ > 0; }
203203

204204
/**
205205
* Marks this loop's isolate as termination-requested. Callable from any
@@ -419,6 +419,10 @@ class EventLoop {
419419
std::atomic<uint64_t> claimCells_[kClaimCells] = {};
420420
// Set by NoteTerminationRequested (any thread), read by PumpUntil.
421421
std::atomic_bool terminationRequested_{false};
422+
// Depth, not a flag: an fd callback can dispatch JS that lands back in
423+
// another callback through a nested drain. Home thread only, like the fd
424+
// callbacks that maintain it.
425+
int looperCallbackDepth_ = 0;
422426
// ordered-lane source with its own bookkeeping (Timers); home-thread only
423427
OrderedTaskSource* timerSource_ = nullptr;
424428
// bare ordered tokens posted before the bind; flushed by Bind

‎test-app/runtime/src/main/cpp/MethodCache.cpp‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,23 +42,22 @@ void MethodCache::Init() {
4242
NS_CHECK(RESOLVE_CONSTRUCTOR_SIGNATURE_ID != nullptr);
4343
}
4444

45-
// Reused for every lookup so a cache hit allocates nothing.
46-
static thread_local std::string s_signatureKey;
4745
static const MethodCache::CacheMethodInfo s_unresolved;
4846

4947
const MethodCache::CacheMethodInfo& MethodCache::ResolveMethodSignature(const string& className, const string& methodName, const FunctionCallbackInfo<Value>& args, bool isStatic) {
5048
CacheMethodInfo method_info;
5149

52-
EncodeSignature(s_signatureKey, className, methodName, args, isStatic);
50+
auto& signatureKey = Runtime::GetRuntime(args.GetIsolate())->GetSignatureKeyScratch();
51+
EncodeSignature(signatureKey, className, methodName, args, isStatic);
5352
{
5453
std::shared_lock<std::shared_mutex> lock(signatureCacheMutex);
55-
auto it = s_mthod_ctor_signature_cache.find(s_signatureKey);
54+
auto it = s_mthod_ctor_signature_cache.find(signatureKey);
5655
if (it != s_mthod_ctor_signature_cache.end()) {
5756
return it->second;
5857
}
5958
}
60-
// Resolving calls into Java, which may call back into JS and reuse s_signatureKey.
61-
string encoded_method_signature = s_signatureKey;
59+
// Resolving calls into Java, which may call back into JS and reuse the scratch key.
60+
string encoded_method_signature = signatureKey;
6261

6362
auto signature = ResolveJavaMethod(args, className, methodName);
6463

@@ -91,15 +90,16 @@ const MethodCache::CacheMethodInfo& MethodCache::ResolveConstructorSignature(con
9190

9291
auto& args = argWrapper.args;
9392
static const string kConstructorName = "<init>";
94-
EncodeSignature(s_signatureKey, fullClassName, kConstructorName, args, false);
93+
auto& signatureKey = Runtime::GetRuntime(args.GetIsolate())->GetSignatureKeyScratch();
94+
EncodeSignature(signatureKey, fullClassName, kConstructorName, args, false);
9595
{
9696
std::shared_lock<std::shared_mutex> lock(signatureCacheMutex);
97-
auto it = s_mthod_ctor_signature_cache.find(s_signatureKey);
97+
auto it = s_mthod_ctor_signature_cache.find(signatureKey);
9898
if (it != s_mthod_ctor_signature_cache.end()) {
9999
return it->second;
100100
}
101101
}
102-
string encoded_ctor_signature = s_signatureKey;
102+
string encoded_ctor_signature = signatureKey;
103103

104104
auto signature = ResolveConstructor(args, javaClass, isInterface);
105105

‎test-app/runtime/src/main/cpp/Runtime.h‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,21 @@ class Runtime {
169169

170170
ObjectManager* GetObjectManager() const;
171171

172+
/*
173+
* Scratch for MethodCache's signature keys, so a cache hit allocates
174+
* nothing. Only for the thread holding the isolate, and not across a
175+
* call that can re-enter JS.
176+
*/
177+
std::string& GetSignatureKeyScratch() {
178+
return m_signatureKeyScratch;
179+
}
180+
181+
// Each default-overriding class's defaultOverrides__ns field, or null
182+
// when the class has none. Only for the thread holding the isolate.
183+
robin_hood::unordered_map<jclass, jfieldID>& GetDefaultOverridesFields() {
184+
return m_defaultOverridesFields;
185+
}
186+
172187
AdmissionGate& GetAdmissionGate() {
173188
return m_admissionGate;
174189
}
@@ -400,6 +415,10 @@ class Runtime {
400415
bool m_isMainThread = false;
401416
bool m_destroyed = false;
402417

418+
std::string m_signatureKeyScratch;
419+
420+
robin_hood::unordered_map<jclass, jfieldID> m_defaultOverridesFields;
421+
403422
// This isolate's performance time origin, captured at isolate
404423
// creation: the monotonic clock reading now() is relative to, and the
405424
// wall-clock milliseconds that reading corresponds to.

0 commit comments

Comments
 (0)