diff --git a/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js b/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js index a69f4cc4a..668028ba2 100644 --- a/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js +++ b/test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js @@ -18,11 +18,24 @@ describe("Runtime-bound Java->JS dispatch", function () { } var originalTimeout; + // Set by a spec whose comparer threads and polls must not outlive it, even + // when jasmine times it out. + var comparingWorker = null; + // One per spec: a callback checks the token its spec captured, so a poll left + // pending by a timed-out spec stays cancelled once the next spec starts. + var currentSpec = null; beforeEach(function () { originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; + currentSpec = { ended: false }; }); afterEach(function () { + currentSpec.ended = true; + if (comparingWorker !== null) { + comparingWorker.terminate(); + comparingWorker = null; + Holder.stopComparing(5000); + } jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; Holder.clear(); }); @@ -65,11 +78,15 @@ describe("Runtime-bound Java->JS dispatch", function () { }); it("drops calls to an object whose worker has terminated", function (done) { + var spec = currentSpec; startWorker(function (worker) { worker.terminate(); var deadline = Date.now() + 10000; (function poll() { + if (spec.ended) { + return; + } // Until teardown completes a call may still be answered. var result; try { @@ -92,6 +109,59 @@ describe("Runtime-bound Java->JS dispatch", function () { }); }); + // Callers on other threads take the worker's isolate while it terminates: each call is + // answered or dropped, never run against an isolate that is being torn down. + it("answers or drops calls other threads make while the worker terminates", function (done) { + if (!multithreaded) { + // Calls are posted to the worker's looper in this mode, not run under its lock. + pending("needs android.enableMultithreadedJavascript"); + } + + var spec = currentSpec; + // Each wait well inside the spec timeout, so a hang fails with its cause. + function waitFor(condition, what, then) { + var deadline = Date.now() + 5000; + (function poll() { + if (spec.ended) { + return; + } + if (condition()) { + then(); + } else if (Date.now() > deadline) { + fail("timed out waiting for " + what); + done(); + } else { + setTimeout(poll, 20); + } + })(); + } + + comparingWorker = startWorker(function (worker) { + if (spec.ended) { + return; + } + // A comparer stops once it has had 20 dropped calls in a row: by then the worker + // has been torn down, and the calls it had in flight overlapped that teardown. + Holder.startComparing("comparable", 4, 20); + waitFor(function () { + return Holder.hasCompared(42); + }, "a call answered by the live worker", function () { + worker.terminate(); + waitFor(function () { + return Holder.comparersFinished(); + }, "every comparer to see its calls dropped", function () { + comparingWorker = null; + var results = Array.prototype.slice.call(Holder.stopComparing(5000)); + expect(results).toContain(0); + results.forEach(function (result) { + expect([42, 0]).toContain(result); + }); + done(); + }); + }); + }); + }); + it("releases a caller whose queued call is discarded when the worker closes", function (done) { if (multithreaded) { // Calls are never queued on the worker's looper in this mode. diff --git a/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java b/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java index 4e84f14a3..dfcfc49b9 100644 --- a/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java +++ b/test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java @@ -1,5 +1,8 @@ package com.tns.tests; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** @@ -40,4 +43,79 @@ public void run() { public static int compare(String key) { return ((Comparable) objects.get(key)).compareTo(""); } + + // Results stopComparing reports for a comparison that threw, and for a comparer + // thread still running at its deadline. + public static final int THREW = Integer.MIN_VALUE; + public static final int STUCK = Integer.MAX_VALUE; + + private static final List comparers = new ArrayList<>(); + private static final Set compared = ConcurrentHashMap.newKeySet(); + private static volatile boolean comparing; + + public static boolean hasCompared(int result) { + return compared.contains(result); + } + + /* + * Keeps calling compareTo on objects[key] from `threads` new threads, each with a new + * object as the argument (so the call registers it from that thread), until + * stopComparing() or until the thread has had `zerosToStop` results of 0 in a row. + */ + public static synchronized void startComparing(final String key, int threads, final int zerosToStop) { + compared.clear(); + comparing = true; + for (int i = 0; i < threads; i++) { + Thread thread = new Thread(new Runnable() { + @Override + @SuppressWarnings("unchecked") + public void run() { + Comparable comparable = (Comparable) objects.get(key); + int zeros = 0; + while (comparing && zeros < zerosToStop) { + int result; + try { + result = comparable.compareTo(new Object()); + } catch (Throwable t) { + result = THREW; + } + compared.add(result); + zeros = result == 0 ? zeros + 1 : 0; + } + } + }, "RuntimeBoundHolder-comparer-" + i); + comparers.add(thread); + thread.start(); + } + } + + public static synchronized boolean comparersFinished() { + for (Thread thread : comparers) { + if (thread.isAlive()) { + return false; + } + } + return true; + } + + // Stops the comparing threads, waiting up to timeoutMillis for them; returns every + // distinct result, with THREW for a throw and STUCK if a thread is still running. + public static synchronized int[] stopComparing(long timeoutMillis) throws InterruptedException { + comparing = false; + long deadline = System.currentTimeMillis() + timeoutMillis; + for (Thread thread : comparers) { + thread.join(Math.max(1, deadline - System.currentTimeMillis())); + if (thread.isAlive()) { + compared.add(STUCK); + } + } + comparers.clear(); + // A thread still running can add results while this copies them. + Integer[] snapshot = compared.toArray(new Integer[0]); + int[] results = new int[snapshot.length]; + for (int i = 0; i < snapshot.length; i++) { + results[i] = snapshot[i]; + } + return results; + } } diff --git a/test-app/runtime/CMakeLists.txt b/test-app/runtime/CMakeLists.txt index 8f64c421d..6a792c596 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -221,6 +221,7 @@ add_library( src/main/cpp/Profiler.cpp src/main/cpp/ReadWriteLock.cpp src/main/cpp/Runtime.cpp + src/main/cpp/RuntimeGates.cpp src/main/cpp/RuntimeState.cpp src/main/cpp/SimpleAllocator.cpp src/main/cpp/SimpleProfiler.cpp diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index d576841cb..4e8ebcbae 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -1,4 +1,5 @@ #include "Runtime.h" +#include "RuntimeGates.h" #include @@ -137,6 +138,7 @@ Runtime::Runtime(JNIEnv* env, jobject runtime, int id) m_runtime = env->NewGlobalRef(runtime); m_objectManager = new ObjectManager(m_runtime); m_state = std::make_unique(); + RuntimeGates::Open(id, this); { std::lock_guard lock(s_runtimeCacheMutex); s_id2RuntimeCache.emplace(id, this); @@ -294,10 +296,13 @@ Runtime::~Runtime() { } /* - * Idempotent backstop for the erase DestroyRuntime does: a bootstrap that - * failed before PrepareV8Runtime ran never reached it. The isolate entry is - * matched on value so it cannot evict a new runtime that reused the pointer. + * Idempotent backstops for the gate retirement and the erase the teardown + * does: a bootstrap that failed before PrepareV8Runtime ran never reached + * them. The gate goes first, while every member a pinned thread may read is + * still alive. The isolate entry is matched on value so it cannot evict a + * new runtime that reused the pointer. */ + RuntimeGates::WaitUntilUnpinnedAndRetire(m_id); { std::lock_guard lock(s_runtimeCacheMutex); s_id2RuntimeCache.erase(m_id); @@ -895,16 +900,18 @@ void Runtime::UnwindFailedInit() { /* * Reuses the two teardown windows rather than adding a third cleanup path. * Every step DestroyRuntime takes is null-tolerant, which is what makes it - * usable on a runtime that never finished building; the Locker is reentrant, - * so it does not matter whether the failure unwound past the one - * PrepareV8Runtime holds. + * usable on a runtime that never finished building. The caller must not + * hold the isolate's Locker: the wait for pins below would deadlock against + * a pinned thread waiting for it. */ if (m_isolate != nullptr) { + NS_DCHECK(!v8::Locker::IsLocked(m_isolate)); { v8::Locker locker(m_isolate); Isolate::Scope isolateScope(m_isolate); DestroyRuntime(); } + RuntimeGates::WaitUntilUnpinnedAndRetire(m_id); m_isolate->Dispose(); m_isolate = nullptr; } @@ -1279,6 +1286,10 @@ double Runtime::PerformanceNowMillis() { void Runtime::DestroyRuntime() { NS_CHECK(std::this_thread::get_id() == m_ownerThread); + NS_DCHECK(v8::Locker::IsLocked(m_isolate)); + // A thread that pinned this runtime and then waited for the Locker drops + // its call when it finds this set. + m_destroyed = true; CrashBreadcrumbs::UnregisterRuntime(m_id); { std::lock_guard lock(s_runtimeCacheMutex); @@ -1389,6 +1400,10 @@ void Runtime::DestroyRuntime() { if (m_state != nullptr) { m_state->Clear(); } + + // New pins are refused from here on; the isolate is disposed only once the + // threads already pinned have let go. + RuntimeGates::Close(m_id); } Local Runtime::GetContext() { diff --git a/test-app/runtime/src/main/cpp/Runtime.h b/test-app/runtime/src/main/cpp/Runtime.h index 77913df69..c51bff845 100644 --- a/test-app/runtime/src/main/cpp/Runtime.h +++ b/test-app/runtime/src/main/cpp/Runtime.h @@ -209,6 +209,10 @@ class Runtime { jboolean PassExceptionToJsNative(JNIEnv* env, jobject obj, jthrowable exception, jstring message, jstring fullStackTrace, jstring jsStackTrace, jboolean isDiscarded); void DestroyRuntime(); + // Read under the isolate's Locker, which DestroyRuntime holds when it + // sets it. + bool IsDestroyed() const { return m_destroyed; } + void Lock(); void Unlock(); @@ -394,6 +398,7 @@ class Runtime { // Decided by ElectMainRuntime, before anything can read it. bool m_isMainThread = false; + bool m_destroyed = false; // This isolate's performance time origin, captured at isolate // creation: the monotonic clock reading now() is relative to, and the diff --git a/test-app/runtime/src/main/cpp/RuntimeGates.cpp b/test-app/runtime/src/main/cpp/RuntimeGates.cpp new file mode 100644 index 000000000..8f2430641 --- /dev/null +++ b/test-app/runtime/src/main/cpp/RuntimeGates.cpp @@ -0,0 +1,109 @@ +#include "RuntimeGates.h" + +#include +#include +#include +#include +#include + +#include "Runtime.h" +#include "robin_hood.h" + +namespace tns { +namespace RuntimeGates { + +// The pin count shifted left by one, and kClosed. Pins are taken and the gate +// closed under the gates' lock; a pin is let go of with one atomic decrement, +// after which the unpinning thread never touches the gate: a waiting teardown +// may free it as soon as it reads no pins. +constexpr uint32_t kClosed = 1; +constexpr uint32_t kPin = 2; + +struct Gate { + Runtime* runtime = nullptr; + std::atomic state{0}; +}; + +namespace { + +std::mutex& GatesMutex() { + static auto* mutex = new std::mutex(); + return *mutex; +} + +std::condition_variable& Unpinned() { + static auto* unpinned = new std::condition_variable(); + return *unpinned; +} + +// Never destroyed: process exit runs static destructors while other threads +// may still be pinning. +// Boxed: a pin holds its gate's address across rehashes. +robin_hood::unordered_map>& Gates() { + static auto* gates = new robin_hood::unordered_map>(); + return *gates; +} + +} // namespace + +void Open(int id, Runtime* runtime) { + auto gate = std::make_unique(); + gate->runtime = runtime; + std::lock_guard lock(GatesMutex()); + Gates()[id] = std::move(gate); +} + +Gate* TryPin(int id, Runtime** runtime) { + std::lock_guard lock(GatesMutex()); + auto it = Gates().find(id); + if (it == Gates().end() || (it->second->state.load(std::memory_order_relaxed) & kClosed) != 0) { + return nullptr; + } + Gate* gate = it->second.get(); + gate->state.fetch_add(kPin, std::memory_order_relaxed); + *runtime = gate->runtime; + return gate; +} + +int TryGenerateObjectId(int id) { + std::lock_guard lock(GatesMutex()); + auto it = Gates().find(id); + if (it == Gates().end() || (it->second->state.load(std::memory_order_relaxed) & kClosed) != 0) { + return -1; + } + return it->second->runtime->GenerateNewObjectId(nullptr, nullptr); +} + +void Unpin(Gate* gate) { + // Release: what the pinned thread did happens before the teardown that reads no pins. + if (gate->state.fetch_sub(kPin, std::memory_order_acq_rel) == (kPin | kClosed)) { + // Taking the lock orders the notify after a waiter's check of the state. + std::lock_guard lock(GatesMutex()); + Unpinned().notify_all(); + } +} + +void Close(int id) { + std::lock_guard lock(GatesMutex()); + auto it = Gates().find(id); + if (it != Gates().end()) { + it->second->state.fetch_or(kClosed, std::memory_order_relaxed); + } +} + +void WaitUntilUnpinnedAndRetire(int id) { + std::unique_lock lock(GatesMutex()); + auto it = Gates().find(id); + if (it == Gates().end()) { + return; + } + Gate* gate = it->second.get(); + gate->state.fetch_or(kClosed, std::memory_order_relaxed); + Unpinned().wait(lock, [gate]() { + return gate->state.load(std::memory_order_acquire) == kClosed; + }); + Gates().erase(id); +} + +} // namespace RuntimeGates +} // namespace tns diff --git a/test-app/runtime/src/main/cpp/RuntimeGates.h b/test-app/runtime/src/main/cpp/RuntimeGates.h new file mode 100644 index 000000000..d557ce998 --- /dev/null +++ b/test-app/runtime/src/main/cpp/RuntimeGates.h @@ -0,0 +1,58 @@ +#ifndef RUNTIMEGATES_H_ +#define RUNTIMEGATES_H_ + +namespace tns { + +class Runtime; + +/* + * One gate per runtime, keyed by its id (ids are never reused); the iOS + * runtime's IsolateGates. A thread entering another thread's runtime pins the + * gate before it waits for the runtime's Locker and until it lets go of it. + * The runtime's teardown closes the gate last, under the Locker, and disposes + * the isolate and frees the runtime only once no pin is held, so a pinned + * runtime and its isolate stay allocated. A missing gate reads as closed. + */ +namespace RuntimeGates { +struct Gate; +// Before the runtime can be found by id. +void Open(int id, Runtime* runtime); +// The pinned gate, and its runtime in *runtime; null once the gate is closed, +// when the runtime may already be freed. +Gate* TryPin(int id, Runtime** runtime); +// Lock-free unless it lets go of the last pin of a closed gate. +void Unpin(Gate* gate); +// A new object id from the runtime, or -1 once the gate is closed. Holds the +// gates' lock rather than a pin: the runtime is freed only after its gate is +// retired under that lock. +int TryGenerateObjectId(int id); +// From the teardown, holding the runtime's Locker. +void Close(int id); +// Before Isolate::Dispose and before the runtime is freed, without the +// runtime's Locker: a pinned thread may be waiting for it. Drops the gate. +void WaitUntilUnpinnedAndRetire(int id); +} // namespace RuntimeGates + +// Owns a pin for its scope. Declare it before the Locker it guards, so the +// Locker is released first. +class RuntimePin { + public: + explicit RuntimePin(int id) : m_gate(RuntimeGates::TryPin(id, &m_runtime)) {} + ~RuntimePin() { + if (m_gate != nullptr) { + RuntimeGates::Unpin(m_gate); + } + } + RuntimePin(const RuntimePin&) = delete; + RuntimePin& operator=(const RuntimePin&) = delete; + // Null when the pin was refused. + Runtime* runtime() const { return m_runtime; } + + private: + Runtime* m_runtime = nullptr; + RuntimeGates::Gate* m_gate; +}; + +} // namespace tns + +#endif /* RUNTIMEGATES_H_ */ diff --git a/test-app/runtime/src/main/cpp/WorkerWrapper.cpp b/test-app/runtime/src/main/cpp/WorkerWrapper.cpp index c36615cd3..cba9672ea 100644 --- a/test-app/runtime/src/main/cpp/WorkerWrapper.cpp +++ b/test-app/runtime/src/main/cpp/WorkerWrapper.cpp @@ -1,4 +1,5 @@ #include "WorkerWrapper.h" +#include "RuntimeGates.h" #include #include @@ -784,6 +785,9 @@ void WorkerWrapper::BackgroundLooper(std::shared_ptr self) { isolate->RemoveNearHeapLimitCallback(WorkerWrapper::OnNearHeapLimit, 0); runtime_->DestroyRuntime(); } + // Without the Locker: a thread pinned in a Java->JS call may be + // waiting for it, and lets go once it finds the runtime unregistered. + RuntimeGates::WaitUntilUnpinnedAndRetire(runtime_->GetId()); isolate->Dispose(); // Dispose freed the isolate's memory, so its address can be reused by // a concurrent Isolate::New - drop the platform's loop entry now, not diff --git a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp index 8358e8812..66b891175 100644 --- a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp +++ b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp @@ -1,10 +1,12 @@ #include "V8StringConstants.h" #include "Runtime.h" +#include "RuntimeGates.h" #include "NativeScriptException.h" #include "CallbackHandlers.h" #include "ArgConverter.h" #include "MetadataNode.h" #include +#include #include #include #include @@ -136,6 +138,63 @@ Runtime* TryGetRuntime(int runtimeId) { return runtime; } +namespace { + +/* + * A Java->JS entry's hold on a runtime: its Locker, after the admission gate + * when `admit`. Entering another thread's runtime pins it first (RuntimeGates, + * as the iOS runtime's native callbacks do), so a runtime tearing down while + * this thread waits for the Locker cannot dispose its isolate or free itself + * before the wait is over, and is found destroyed once the Locker is granted. + * Get() is null when the call is dropped: the runtime is gone or shutting + * down. + */ +class RuntimeEntry { +public: + RuntimeEntry(jint runtimeId, bool admit) { + auto runtime = Runtime::GetCurrentRuntime(); + // This thread's own runtime is torn down only on this thread. + if (runtime == nullptr || runtime->GetId() != runtimeId) { + m_pin.emplace(runtimeId); + runtime = m_pin->runtime(); + if (runtime == nullptr) { + return; + } + } + auto isolate = runtime->GetIsolate(); + // A runtime whose bootstrap failed before it had an isolate. + if (isolate == nullptr) { + return; + } + if (admit) { + m_admission.emplace(runtime->GetAdmissionGate(), isolate); + } + m_locker.emplace(isolate); + if (runtime->IsDestroyed()) { + return; + } + m_runtime = runtime; + } + + tns::Runtime* Get() const { return m_runtime; } + +private: + tns::Runtime* m_runtime = nullptr; + // Released in reverse: the Locker, the admission gate, then the pin. + std::optional m_pin; + std::optional m_admission; + std::optional m_locker; +}; + +// Same tag and wording as the Java side's dropped calls (Runtime.logDiscardedCall). +void LogDropped(jint runtimeId, const std::string& what) { + __android_log_print(ANDROID_LOG_WARN, "Warning", + "NativeScript discarding %s: runtime id=%d is shutting down", + what.c_str(), runtimeId); +} + +} // namespace + extern "C" JNIEXPORT void Java_com_tns_Runtime_runModule(JNIEnv* _env, jobject obj, jint runtimeId, jstring scriptFile) { JEnv::EntryScope envScope(_env); auto runtime = TryGetRuntime(runtimeId); @@ -201,14 +260,14 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _en JEnv::EntryScope envScope(_env); jobject result = nullptr; - auto runtime = TryGetRuntime(runtimeId); + RuntimeEntry entry(runtimeId, true); + auto runtime = entry.Get(); if (runtime == nullptr) { + LogDropped(runtimeId, "call to \"" + ArgConverter::jstringToString(methodName) + "\""); return result; } auto isolate = runtime->GetIsolate(); - AdmissionScope admission(runtime->GetAdmissionGate(), isolate); - v8::Locker locker(isolate); v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handleScope(isolate); auto context = runtime->GetContext(); @@ -238,14 +297,14 @@ extern "C" JNIEXPORT jobject Java_com_tns_Runtime_callJSMethodNative(JNIEnv* _en extern "C" JNIEXPORT void Java_com_tns_Runtime_createJSInstanceNative(JNIEnv* _env, jobject obj, jint runtimeId, jobject javaObject, jint javaObjectID, jstring className) { JEnv::EntryScope envScope(_env); - auto runtime = TryGetRuntime(runtimeId); + RuntimeEntry entry(runtimeId, true); + auto runtime = entry.Get(); if (runtime == nullptr) { + LogDropped(runtimeId, "the JS instance of a " + ArgConverter::jstringToString(className)); return; } auto isolate = runtime->GetIsolate(); - AdmissionScope admission(runtime->GetAdmissionGate(), isolate); - v8::Locker locker(isolate); v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handleScope(isolate); auto context = runtime->GetContext(); @@ -269,11 +328,14 @@ extern "C" JNIEXPORT void Java_com_tns_Runtime_createJSInstanceNative(JNIEnv* _e // @CriticalNative ABI: no JNIEnv* / jclass. static jint generateNewObjectIdCritical_impl(jint runtimeId) { try { - auto runtime = TryGetRuntime(runtimeId); - if (runtime == nullptr) { - return 0; + auto current = Runtime::GetCurrentRuntime(); + if (current != nullptr && current->GetId() == runtimeId) { + return current->GenerateNewObjectId(nullptr, nullptr); } - return runtime->GenerateNewObjectId(nullptr, nullptr); + // Java registers a call's arguments on the calling thread, without the + // isolate lock, so this can run on any thread while the runtime tears + // down. -1 is ObjectTable.NO_ID; Java drops the call it was for. + return RuntimeGates::TryGenerateObjectId(runtimeId); } catch (NativeScriptException& e) { e.ReThrowToJava(); } catch (std::exception e) { @@ -323,13 +385,14 @@ extern "C" JNIEXPORT void Java_com_tns_Runtime_unlock(JNIEnv* env, jobject obj, } extern "C" JNIEXPORT jboolean Java_com_tns_Runtime_passExceptionToJsNative(JNIEnv* env, jobject obj, jint runtimeId, jthrowable exception, jstring message, jstring fullStackTrace, jstring jsStackTrace, jboolean isDiscarded) { - auto runtime = TryGetRuntime(runtimeId); + RuntimeEntry entry(runtimeId, false); + auto runtime = entry.Get(); if (runtime == nullptr) { + LogDropped(runtimeId, "an exception report"); return JNI_FALSE; } auto isolate = runtime->GetIsolate(); - v8::Locker locker(isolate); v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handleScope(isolate); auto context = runtime->GetContext(); diff --git a/test-app/runtime/src/main/java/com/tns/ObjectTable.java b/test-app/runtime/src/main/java/com/tns/ObjectTable.java index eec847e5b..460fadcbe 100644 --- a/test-app/runtime/src/main/java/com/tns/ObjectTable.java +++ b/test-app/runtime/src/main/java/com/tns/ObjectTable.java @@ -21,6 +21,7 @@ final class ObjectTable { static final long FRESH = 1L << 32; interface IdSource { + // NO_ID when there is no id to give. int newId(); } @@ -104,7 +105,8 @@ private void putStrongLocked(int id, Object obj, int hash) { /** * The id obj is registered under, registering it strongly under a new id from ids when * it has none; FRESH is set in the result when this call registered it. The lookup and - * the insert happen under one lock, so concurrent calls agree on one id. + * the insert happen under one lock, so concurrent calls agree on one id. NO_ID (with + * nothing registered) when obj has no id and ids gives none. */ long findOrRegister(Object obj, IdSource ids) { synchronized (this) { @@ -114,6 +116,9 @@ long findOrRegister(Object obj, IdSource ids) { return id & 0xFFFFFFFFL; } id = ids.newId(); + if (id == NO_ID) { + return NO_ID & 0xFFFFFFFFL; + } putStrongLocked(id, obj, hash); return (id & 0xFFFFFFFFL) | FRESH; } diff --git a/test-app/runtime/src/main/java/com/tns/Runtime.java b/test-app/runtime/src/main/java/com/tns/Runtime.java index c9e5ea27f..f67c9e469 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -1471,7 +1471,8 @@ private static final class PackagedArgs { private static final PackagedArgs NO_ARGS = new PackagedArgs(0, null, null); // If a javaObject has no javaObjectID, meaning no JavaScript object exists - // for it yet, it is assigned one. + // for it yet, it is assigned one. Null when no id can be had: the runtime is + // shutting down and the call has to be dropped. private PackagedArgs packageArgs(Object... args) { int len = (args != null) ? args.length : 0; if (len == 0) { @@ -1538,6 +1539,9 @@ private PackagedArgs packageArgs(Object... args) { // in with new objects only serialize on creating their wrappers. long found = objectTable.findOrRegister(value, objectIds); id = (int) found; + if (id == ObjectTable.NO_ID) { + return null; + } if ((found & ObjectTable.FRESH) != 0) { fresh = FRESH_ARG; } @@ -1660,6 +1664,10 @@ private Object dispatchCallJSMethodNative(final Object javaObject, int objectIdH if (enableMultithreadedJavascript || isWorkThread) { PackagedArgs packagedArgs = packageArgs(tmpArgs); + if (packagedArgs == null) { + return discardCall(methodName, retType, "runtime id=" + getRuntimeId() + " (workerId=" + workerId + + ") is shutting down"); + } long[] primitiveResult = newPrimitiveResult(returnType); try { // A hint: other threads may be writing the table, so native re-checks it under the @@ -1668,10 +1676,9 @@ private Object dispatchCallJSMethodNative(final Object javaObject, int objectIdH objectIdHint != ObjectTable.NO_ID ? objectIdHint : objectTable.findId(javaObject), methodName, MethodNameIds.idOf(methodName), returnType, isConstructor, packagedArgs.count, packagedArgs.values, packagedArgs.refs, primitiveResult); ret = takePrimitiveResult(ret, returnType, primitiveResult); } catch (NativeScriptException e) { - // With multithreaded JS the owner can be torn down between the - // routing check and the native call, which then throws - // "Cannot find runtime"; that is the same lifecycle race the - // other dead-owner paths drop. + // With multithreaded JS the owner can stop accepting work while + // the call runs on this thread; an exception from such a call is + // the same lifecycle race the other dead-owner paths drop. if (!isAcceptingWork()) { return discardCall(methodName, retType, "runtime id=" + getRuntimeId() + " (workerId=" + workerId + ") terminated during the call"); diff --git a/test-app/runtime/src/test/java/com/tns/ObjectTableTest.java b/test-app/runtime/src/test/java/com/tns/ObjectTableTest.java index e39fa3740..93356ba35 100644 --- a/test-app/runtime/src/test/java/com/tns/ObjectTableTest.java +++ b/test-app/runtime/src/test/java/com/tns/ObjectTableTest.java @@ -335,6 +335,23 @@ public int newId() { assertEquals(1, table.size()); } + @Test + public void registersNothingWhenNoIdIsGiven() { + ObjectTable table = new ObjectTable(); + Object a = new Object(); + + long found = table.findOrRegister(a, new ObjectTable.IdSource() { + @Override + public int newId() { + return ObjectTable.NO_ID; + } + }); + assertEquals(ObjectTable.NO_ID, (int) found); + assertFalse((found & ObjectTable.FRESH) != 0); + assertEquals(ObjectTable.NO_ID, table.findId(a)); + assertEquals(0, table.size()); + } + @Test public void matchesReferenceMapsUnderRandomOperations() { Random random = new Random(42);