diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/SerialExecutor.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/SerialExecutor.java
index dc3d2931..41a70b9c 100644
--- a/webrtc/src/main/java/dev/onvoid/webrtc/client/SerialExecutor.java
+++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/SerialExecutor.java
@@ -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;
/**
@@ -30,7 +29,8 @@
* as if on a thread of their own.
*
* 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.
*
* 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
@@ -38,10 +38,11 @@
* 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.
*
- * 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 {
@@ -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 dropped;
synchronized (tasks) {
@@ -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));
}
@@ -180,7 +183,7 @@ private void schedule() {
task.dropped.run();
}
catch (Throwable error) {
- errorHandler.accept(error);
+ report(error);
}
}
}
@@ -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) {
@@ -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();
diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java
index 3d9aaa42..9d145094 100644
--- a/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java
+++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/WebRtc.java
@@ -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.
+ }
}
diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java
index f4cf20d8..d7a69c3e 100644
--- a/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java
+++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/PeerTests.java
@@ -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 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
diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/SerialExecutorTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/SerialExecutorTests.java
index ef8a890a..245d3448 100644
--- a/webrtc/src/test/java/dev/onvoid/webrtc/client/SerialExecutorTests.java
+++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/SerialExecutorTests.java
@@ -236,6 +236,115 @@ void throwingTaskReported() {
assertEquals(Collections.singletonList(failure), errors);
}
+ @Test
+ void throwingHandlerKeepsTasks() {
+ List ran = new ArrayList<>();
+ IllegalStateException failure = new IllegalStateException("handler failed");
+ SerialExecutor failing = new SerialExecutor(pool, work, error -> {
+ throw failure;
+ }, false, null);
+
+ List uncaught = whileUncaughtHandlerThrows(() -> {
+ failing.execute(() -> {
+ throw new IllegalStateException("task failed");
+ });
+ failing.execute(() -> ran.add("next"));
+ pool.runAll();
+
+ // Still able to start a turn of its own.
+ failing.execute(() -> ran.add("later"));
+ pool.runAll();
+ });
+
+ assertEquals(Arrays.asList("next", "later"), ran);
+ assertEquals(Collections.singletonList(failure), uncaught);
+ assertEquals(0, work.snapshot().queued());
+ assertEquals(0, work.snapshot().active());
+ }
+
+ @Test
+ void throwingHandlerKeepsFallbacks() {
+ List dropped = new ArrayList<>();
+ SerialExecutor failing = new SerialExecutor(pool, work, error -> {
+ throw new IllegalStateException("handler failed");
+ }, false, null);
+
+ whileUncaughtHandlerThrows(() -> {
+ for (int i = 0; i < SerialExecutor.BATCH_SIZE; i++) {
+ failing.execute(() -> { });
+ }
+ failing.execute(() -> { }, () -> {
+ dropped.add(1);
+ throw new IllegalStateException("fallback failed");
+ });
+ failing.execute(() -> { }, () -> dropped.add(2));
+
+ pool.rejecting(true);
+ pool.runNext();
+ });
+
+ // The futures these complete must not stay open.
+ assertEquals(Arrays.asList(1, 2), dropped);
+ }
+
+ @Test
+ void abortedTurnSchedulesNext() {
+ List ran = new ArrayList<>();
+ IllegalStateException failure = new IllegalStateException("clock failed");
+ boolean[] clockFails = new boolean[1];
+ Workload workload = new Workload(() -> {
+ if (clockFails[0]) {
+ throw failure;
+ }
+ return 0;
+ });
+ SerialExecutor aborted = new SerialExecutor(pool, workload, errors::add, false, null);
+
+ aborted.execute(() -> {
+ ran.add("first");
+ clockFails[0] = true;
+ });
+ aborted.execute(() -> ran.add("second"));
+ pool.runNext();
+
+ assertEquals(Collections.singletonList("first"), ran);
+ assertEquals(Collections.singletonList(failure), errors);
+ assertEquals(1, pool.queued());
+
+ clockFails[0] = false;
+ pool.runAll();
+
+ assertEquals(Arrays.asList("first", "second"), ran);
+ }
+
+ @Test
+ void failingExecutorRunsFallback() {
+ List ran = new ArrayList<>();
+ IllegalStateException failure = new IllegalStateException("Toolkit gone");
+ boolean[] executorFails = { true };
+ SerialExecutor failing = new SerialExecutor(task -> {
+ if (executorFails[0]) {
+ throw failure;
+ }
+ pool.execute(task);
+ }, work, errors::add, false, null);
+
+ failing.execute(() -> ran.add("task"), () -> ran.add("fallback"));
+
+ assertEquals(Collections.singletonList("fallback"), ran);
+ assertEquals(1, errors.size(), () -> "Errors: " + errors);
+ assertSame(failure, errors.get(0).getCause());
+ assertEquals(1, work.snapshot().dropped());
+ assertEquals(0, work.snapshot().queued());
+
+ // The next task tries the executor again.
+ executorFails[0] = false;
+ failing.execute(() -> ran.add("later"));
+ pool.runAll();
+
+ assertEquals(Arrays.asList("fallback", "later"), ran);
+ }
+
@Test
void eventThreadMarked() {
SerialExecutor events = new SerialExecutor(pool, errors::add, true, "events-test");
@@ -257,6 +366,32 @@ void eventThreadMarked() {
assertTrue(errors.isEmpty(), () -> "Errors: " + errors);
}
+ /**
+ * Runs the action while the uncaught exception handler of this thread
+ * throws, as the handler of an application may.
+ *
+ * @return what the handler received.
+ */
+ private static List whileUncaughtHandlerThrows(Runnable action) {
+ List uncaught = new ArrayList<>();
+ Thread thread = Thread.currentThread();
+ Thread.UncaughtExceptionHandler previous = thread.getUncaughtExceptionHandler();
+
+ thread.setUncaughtExceptionHandler((failed, error) -> {
+ uncaught.add(error);
+ throw new IllegalStateException("uncaught exception handler failed");
+ });
+
+ try {
+ action.run();
+ }
+ finally {
+ thread.setUncaughtExceptionHandler(previous);
+ }
+
+ return uncaught;
+ }
+
private static List range(int from, int to) {
return IntStream.range(from, to).boxed().collect(Collectors.toList());
}