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
124 changes: 75 additions & 49 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/SerialExecutor.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.function.Consumer;

/**
Expand All @@ -30,18 +29,20 @@
* as if on a thread of their own.
* <p>
* A task that throws does not stop the ones after it; its exception goes to
* the error handler.
* the error handler. An error handler that throws stops nothing either, and
* however a turn ends, the tasks left get the next one.
* <p>
* Each turn on the executor runs at most {@link #BATCH_SIZE} tasks and ends
* once it has run for {@link #TURN_NANOS}, after which the executor queues
* its next turn behind those of the others. A pool with a fixed number of
* threads and a FIFO queue thus serves every executor in turn, however slow
* the tasks of some of them are, and it holds at most one turn of each.
* <p>
* When the executor rejects the tasks, they are dropped, and those submitted
* with a fallback have it run instead, on the thread that found them
* rejected. A rejection by an executor that was not shut down goes to the
* error handler as well, since it loses work the application expects.
* When the executor rejects the tasks, or fails in any other way to take
* them, they are dropped, and those submitted with a fallback have it run
* instead, on the thread that found them rejected. A rejection by an executor
* that was not shut down goes to the error handler as well, since it loses
* work the application expects.
*/
final class SerialExecutor implements Executor {

Expand Down Expand Up @@ -155,7 +156,9 @@ private void schedule() {
try {
executor.execute(this::drain);
}
catch (RejectedExecutionException e) {
catch (Throwable e) {
// Not only a rejection: an executor of the application may throw
// anything, and the tasks would wait for a turn that never comes.
List<Task> dropped;

synchronized (tasks) {
Expand All @@ -169,7 +172,7 @@ private void schedule() {
// and then nothing is lost that it does not fail itself.
if (!(executor instanceof ExecutorService && ((ExecutorService) executor).isShutdown())) {
workload.dropped(dropped.size());
errorHandler.accept(new WebRtcException("The executor rejected " + dropped.size()
report(new WebRtcException("The executor rejected " + dropped.size()
+ " tasks, which were dropped", e));
}

Expand All @@ -180,7 +183,7 @@ private void schedule() {
task.dropped.run();
}
catch (Throwable error) {
errorHandler.accept(error);
report(error);
}
}
}
Expand All @@ -190,59 +193,55 @@ private void schedule() {
private void drain() {
Thread thread = Thread.currentThread();
String previousName = null;
boolean more = true;

if (threadName != null) {
previousName = thread.getName();
thread.setName(threadName);
}
if (eventThread) {
EVENT_DEPTH.get()[0]++;
}
try {
if (threadName != null) {
previousName = thread.getName();
thread.setName(threadName);
}
if (eventThread) {
EVENT_DEPTH.get()[0]++;
}

runner = thread;
runner = thread;

boolean more = true;
long start = workload.now();
try {
long start = workload.now();

try {
for (int i = 0; i < BATCH_SIZE && (i == 0 || workload.now() - start < TURN_NANOS); i++) {
Task task;
for (int i = 0; i < BATCH_SIZE && (i == 0 || workload.now() - start < TURN_NANOS); i++) {
Task task;

synchronized (tasks) {
task = tasks.poll();
synchronized (tasks) {
task = tasks.poll();

if (task == null) {
scheduled = false;
more = false;
break;
if (task == null) {
scheduled = false;
more = false;
break;
}
if (tasks.isEmpty()) {
workload.idle(backlog);
}
}
if (tasks.isEmpty()) {
workload.idle(backlog);
}
}

workload.started();

try {
task.task.run();
run(task);
}
catch (Throwable e) {
errorHandler.accept(e);
}
finally {
runner = null;

if (eventThread) {
EVENT_DEPTH.get()[0]--;
}
finally {
workload.finished();
if (previousName != null) {
thread.setName(previousName);
}
}
}
finally {
runner = null;

if (eventThread) {
EVENT_DEPTH.get()[0]--;
}
if (previousName != null) {
thread.setName(previousName);
}
catch (Throwable e) {
// Still scheduled, so without a next turn nothing would start one.
report(e);
}

if (more) {
Expand All @@ -251,6 +250,33 @@ private void drain() {
}
}

private void run(Task task) {
workload.started();

try {
task.task.run();
}
catch (Throwable e) {
report(e);
}
finally {
workload.finished();
}
}

/**
* Hands the error to the error handler. This never throws, since the tasks
* left and the fallbacks still have to run.
*/
private void report(Throwable error) {
try {
errorHandler.accept(error);
}
catch (Throwable e) {
WebRtc.uncaught(e);
}
}

private void count(Workload.Tally tally) {
synchronized (tasks) {
Task oldest = tasks.peek();
Expand Down
14 changes: 12 additions & 2 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java
Original file line number Diff line number Diff line change
Expand Up @@ -701,9 +701,19 @@ private static ThreadFactory threads(String prefix) {
};
}

private static void uncaught(Throwable error) {
/**
* Hands the error to the uncaught exception handler of this thread. This
* never throws, so that the thread can go on with the work it still has.
*/
static void uncaught(Throwable error) {
Thread thread = Thread.currentThread();
thread.getUncaughtExceptionHandler().uncaughtException(thread, error);

try {
thread.getUncaughtExceptionHandler().uncaughtException(thread, error);
}
catch (Throwable ignored) {
// There is no one left to tell, and the JVM ignores it just the same.
}
}


Expand Down
37 changes: 37 additions & 0 deletions webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,43 @@ void statsHandlerErrorReported() throws Exception {
}
}

@Test
void failingUncaughtHandlerKeepsEvents() {
// Without an error handler, what a handler throws reaches the uncaught
// exception handler of the thread, which here throws as well. The
// events after it still come.
ManualExecutor pool = new ManualExecutor();
List<String> ran = new ArrayList<>();
Thread thread = Thread.currentThread();
Thread.UncaughtExceptionHandler previous = thread.getUncaughtExceptionHandler();

try (WebRtc runtime = WebRtc.builder()
.audio(AudioMode.HEADLESS)
.eventExecutor(pool)
.build()) {
SerialExecutor events = new SerialExecutor(runtime.eventExecutor, runtime.eventWork,
runtime::reportError, true, null);

thread.setUncaughtExceptionHandler((failed, error) -> {
throw new IllegalStateException("Uncaught exception handler failed");
});

events.execute(() -> {
throw new IllegalStateException("Handler failed");
});
events.execute(() -> ran.add("next"));
pool.runAll();

events.execute(() -> ran.add("later"));
pool.runAll();

assertEquals(Arrays.asList("next", "later"), ran);
}
finally {
thread.setUncaughtExceptionHandler(previous);
}
}

@Test
void statsHandlerKeepsEventExecutor() throws Exception {
// The report of a sample may be read before the timer's thread gets
Expand Down
Loading
Loading