Skip to content

Commit 766e992

Browse files
committed
perf(runtime): skip the jweak check while Java holds the object strongly
Every cache hit in GetJavaObjectByJsObject asked JNI whether the cached weak global ref was cleared (IsSameObject, a thread-state transition). While a linked wrapper's Java side has not been weakened, Java's ObjectTable holds the object strongly under its id, so the jweak cached for that id cannot have been cleared and the check is skipped. Wrappers whose Java side was weakened (and may have been handed back to JS since) keep it. Two cases broke that invariant and are closed here: - A finalizer batch that failed part way could leave objects weakened on the Java side with javaWeakened still false. The flag is now set before the call, so a failure leaves it conservative. - While JS constructs an object, an instance of the same class that Java creates inside the constructor takes the reserved id until registerConstructedInstance replaces it. A jweak cached in that window named the nested instance, so calls on the constructed object reached the nested one (and, once it was collected, relied on the jweak check). The cached entry is now dropped after registration.
1 parent ab9dac6 commit 766e992

6 files changed

Lines changed: 118 additions & 20 deletions

File tree

‎test-app/app/src/main/assets/app/tests/testObjectArgumentPath.js‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,4 +112,66 @@ describe("Object arguments and cached call signatures", function () {
112112
seen.push(empty);
113113
}
114114
});
115+
116+
describe("cached Java objects of linked wrappers", function () {
117+
var Holder = com.tns.tests.WrapperHolder;
118+
119+
function collectJava() {
120+
for (var i = 0; i < 3; i++) {
121+
java.lang.Runtime.getRuntime().gc();
122+
java.lang.System.runFinalization();
123+
}
124+
}
125+
126+
afterEach(function () {
127+
Holder.held = null;
128+
});
129+
130+
it("never pass null for a wrapper whose Java object was collected after Java weakened it", function () {
131+
(function () {
132+
Holder.held = new java.lang.StringBuilder("weakened");
133+
})();
134+
gc();
135+
// Any Java call flushes the collected wrapper, weakening its Java object.
136+
collectJava();
137+
var again = Holder.held;
138+
Holder.held = null;
139+
collectJava();
140+
141+
var passed;
142+
try {
143+
passed = java.util.Collections.singletonList(again).get(0);
144+
} catch (e) {
145+
passed = "threw";
146+
}
147+
expect(passed === again || passed === "threw").toBe(true);
148+
});
149+
150+
it("resolve a reachable wrapper after warm instance calls and a collection", function () {
151+
var sb = new java.lang.StringBuilder("warm");
152+
for (var i = 0; i < 50; i++) {
153+
expect(sb.length()).toBe(4);
154+
}
155+
for (var j = 0; j < 2000; j++) {
156+
new java.lang.Object();
157+
}
158+
gc();
159+
collectJava();
160+
expect(sb.toString()).toBe("warm");
161+
expect(java.util.Collections.singletonList(sb).get(0)).toBe(sb);
162+
});
163+
164+
it("resolve a constructed instance after Java made another of its class during the constructor", function () {
165+
var Outer = com.tns.tests.SelfNesting.extend({
166+
touch: function () {
167+
this.super.touch();
168+
},
169+
selfNestingSpec: true
170+
});
171+
var outer = new Outer(true);
172+
expect(outer.getTag()).toBe(2);
173+
collectJava();
174+
expect(outer.getTag()).toBe(2);
175+
});
176+
});
115177
});
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.tns.tests;
2+
3+
/** Creates an instance of its own runtime class while its constructor runs. */
4+
public class SelfNesting {
5+
private final int tag;
6+
7+
public SelfNesting() {
8+
tag = 1;
9+
}
10+
11+
public SelfNesting(boolean nest) throws Exception {
12+
tag = 2;
13+
if (nest) {
14+
SelfNesting nested = getClass().getConstructor().newInstance();
15+
nested.touch();
16+
}
17+
}
18+
19+
public int getTag() {
20+
return tag;
21+
}
22+
23+
public void touch() {
24+
}
25+
}

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,9 @@ bool CallbackHandlers::RegisterInstance(Isolate *isolate, const Local<Object> &j
275275

276276
jlong usedJavaMemory = env.CallLongMethod(runtime->GetJavaRuntime(), REGISTER_CONSTRUCTED_INSTANCE_ID,
277277
instance, javaObjectID);
278+
// While the constructor ran, an instance of the same class that Java created could take
279+
// this id until the registration above replaced it; a jweak cached then names that one.
280+
objectManager->ForgetCachedJavaObject(javaObjectID);
278281

279282
AdjustAmountOfExternalAllocatedMemory(isolate, usedJavaMemory);
280283

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

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,14 @@ class LRUCache {
5151
NS_CHECK((0 < m_capacity) && (m_capacity < 10000));
5252
}
5353

54-
// Obtain value of the cached function for k
55-
value_type operator()(const key_type& k) {
54+
// Obtain value of the cached function for k. validate=false skips the validity
55+
// callback for a hit the caller knows is still valid.
56+
value_type operator()(const key_type& k, bool validate = true) {
5657

5758
// Attempt to find existing record
5859
auto it = m_key_to_value.find(k);
5960

60-
if (m_cacheValidCallback != nullptr && it != m_key_to_value.end()) {
61+
if (validate && m_cacheValidCallback != nullptr && it != m_key_to_value.end()) {
6162
//check if cache is still valid
6263
if (!m_cacheValidCallback(k, (*it).second.first, m_state)) {
6364
//cache is not valid anymore, evict the key
@@ -122,8 +123,6 @@ class LRUCache {
122123
m_key_tracker.clear();
123124
}
124125

125-
private:
126-
127126
void evictKey(const key_type& key) {
128127
auto it = m_key_to_value.find(key);
129128
if (it != m_key_to_value.end()) {
@@ -135,6 +134,8 @@ class LRUCache {
135134
}
136135
}
137136

137+
private:
138+
138139
// Record a fresh key-value pair in the cache
139140
void insert(const key_type& k, const value_type& v) {
140141
// Method is only called on cache misses

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

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,8 @@ JniLocalRef ObjectManager::GetJavaObjectByJsObject(
110110
if (jsInstanceInfo != nullptr) {
111111
jweak existingObject;
112112
try {
113-
existingObject = GetJavaObjectByID(jsInstanceInfo->javaObjectID);
113+
existingObject = GetJavaObjectByID(jsInstanceInfo->javaObjectID,
114+
jsInstanceInfo->javaWeakened);
114115
} catch (const NativeScriptException& e) {
115116
// this captures usually the error
116117
auto className = GetClassName(jsInstanceInfo->objectClazz);
@@ -286,10 +287,8 @@ bool ObjectManager::IsJsRuntimeObject(const v8::Local<v8::Object>& object) {
286287
internalFieldCount == V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
287288
}
288289

289-
jweak ObjectManager::GetJavaObjectByID(uint32_t javaObjectID) {
290-
jweak obj = m_cache(javaObjectID);
291-
292-
return obj;
290+
jweak ObjectManager::GetJavaObjectByID(uint32_t javaObjectID, bool validate) {
291+
return m_cache(javaObjectID, validate);
293292
}
294293

295294
jobject ObjectManager::GetJavaObjectByIDImpl(uint32_t javaObjectID) {
@@ -682,6 +681,11 @@ void ObjectManager::FlushFinalizedBatch() {
682681
return;
683682
}
684683

684+
// Before the call: one that fails part way may already have weakened some of them.
685+
for (jint id : weaken) {
686+
m_idToObject.Find(id)->javaWeakened = true;
687+
}
688+
685689
JEnv env;
686690
JNIEnv* raw = env;
687691
auto toJava = [raw](const std::vector<jint>& ids) -> jintArray {
@@ -726,8 +730,7 @@ void ObjectManager::FlushFinalizedBatch() {
726730
return;
727731
}
728732

729-
auto settle = [this, raw](const std::vector<jint>& ids, jintArray array,
730-
bool weakened) {
733+
auto settle = [this, raw](const std::vector<jint>& ids, jintArray array) {
731734
if (ids.empty()) {
732735
return;
733736
}
@@ -744,13 +747,10 @@ void ObjectManager::FlushFinalizedBatch() {
744747
continue;
745748
}
746749
state->queued = false;
747-
if (weakened) {
748-
state->javaWeakened = true;
749-
}
750750
}
751751
};
752-
settle(weaken, (jintArray) weakenArray, true);
753-
settle(check, (jintArray) checkArray, false);
752+
settle(weaken, (jintArray) weakenArray);
753+
settle(check, (jintArray) checkArray);
754754
}
755755

756756
void ObjectManager::ReleaseCollectedWrapper(int javaObjectID) {

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

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,10 @@ class ObjectManager {
4949

5050
void UpdateCache(int objectID, jobject obj);
5151

52+
// Drops the jweak cached for objectID, after Java may have registered a different object
53+
// under it.
54+
void ForgetCachedJavaObject(int objectID) { m_cache.evictKey(objectID); }
55+
5256
jclass GetJavaClass(const v8::Local<v8::Object>& instance);
5357

5458
void SetJavaClass(const v8::Local<v8::Object>& instance, jclass clazz);
@@ -182,8 +186,9 @@ class ObjectManager {
182186
// Cleared by ReleaseNativeCounterpart; the registration itself lives until the
183187
// wrapper is collected.
184188
bool linked = true;
185-
// The Java side holds the object weakly; a finalization now only asks
186-
// whether it is still alive.
189+
// The Java side may hold the object weakly; a finalization now only asks
190+
// whether it is still alive. While false, Java holds the object strongly under
191+
// javaObjectID, so a jweak cached for that id still names it.
187192
bool javaWeakened = false;
188193
// Queued in a finalizer batch that has not been flushed yet.
189194
bool queued = false;
@@ -261,7 +266,9 @@ class ObjectManager {
261266
// A flush failed; crossings leave the retry to the delayed task.
262267
bool m_flushBackingOff = false;
263268

264-
jweak GetJavaObjectByID(uint32_t javaObjectID);
269+
// validate=false only while the Java side holds the object strongly: its jweak
270+
// cannot have been cleared then.
271+
jweak GetJavaObjectByID(uint32_t javaObjectID, bool validate);
265272

266273
jobject GetJavaObjectByIDImpl(uint32_t javaObjectID);
267274

0 commit comments

Comments
 (0)