Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions test-app/app/src/main/assets/app/tests/testRuntimeBoundDispatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
Expand Down Expand Up @@ -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 {
Expand All @@ -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.
Expand Down
78 changes: 78 additions & 0 deletions test-app/app/src/main/java/com/tns/tests/RuntimeBoundHolder.java
Original file line number Diff line number Diff line change
@@ -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;

/**
Expand Down Expand Up @@ -40,4 +43,79 @@ public void run() {
public static int compare(String key) {
return ((Comparable<Object>) 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<Thread> comparers = new ArrayList<>();
private static final Set<Integer> 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<Object> comparable = (Comparable<Object>) 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()));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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;
}
}
1 change: 1 addition & 0 deletions test-app/runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 21 additions & 6 deletions test-app/runtime/src/main/cpp/Runtime.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "Runtime.h"
#include "RuntimeGates.h"

#include <console/Console.h>

Expand Down Expand Up @@ -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<RuntimeState>();
RuntimeGates::Open(id, this);
{
std::lock_guard<std::mutex> lock(s_runtimeCacheMutex);
s_id2RuntimeCache.emplace(id, this);
Expand Down Expand Up @@ -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<std::mutex> lock(s_runtimeCacheMutex);
s_id2RuntimeCache.erase(m_id);
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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<std::mutex> lock(s_runtimeCacheMutex);
Expand Down Expand Up @@ -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<Context> Runtime::GetContext() {
Expand Down
5 changes: 5 additions & 0 deletions test-app/runtime/src/main/cpp/Runtime.h
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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
Expand Down
Loading