Skip to content

Commit d9b40cd

Browse files
committed
Handle throws on tasks submitted to thread pools
When we submit a task to a thread pool for asynchronous execution, we are returned a future. Since we submitted to go asynchronous, these futures are not inspected for failure (we would have to block a thread to do that). While we have on failure handlers for exceptions that are thrown during execution, we do not handle throwables that are not exceptions and these end up silently lost. This commit adds a check after the runnable returns that inspects the status of the future. If an unhandled throwable occurred during execution, this throwable is propogated out where it will land in the uncaught exception handler. Relates #28667
1 parent c6f23d4 commit d9b40cd

File tree

2 files changed

+141
-0
lines changed

2 files changed

+141
-0
lines changed

core/src/main/java/org/elasticsearch/common/util/concurrent/ThreadContext.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@
1919
package org.elasticsearch.common.util.concurrent;
2020

2121
import org.apache.lucene.util.CloseableThreadLocal;
22+
import org.elasticsearch.ExceptionsHelper;
2223
import org.elasticsearch.common.io.stream.StreamInput;
2324
import org.elasticsearch.common.io.stream.StreamOutput;
2425
import org.elasticsearch.common.io.stream.Writeable;
26+
import org.elasticsearch.common.logging.ESLoggerFactory;
2527
import org.elasticsearch.common.settings.Setting;
2628
import org.elasticsearch.common.settings.Setting.Property;
2729
import org.elasticsearch.common.settings.Settings;
@@ -33,7 +35,11 @@
3335
import java.util.HashMap;
3436
import java.util.List;
3537
import java.util.Map;
38+
import java.util.Optional;
3639
import java.util.Set;
40+
import java.util.concurrent.CancellationException;
41+
import java.util.concurrent.ExecutionException;
42+
import java.util.concurrent.RunnableFuture;
3743
import java.util.concurrent.atomic.AtomicBoolean;
3844
import java.util.function.Function;
3945
import java.util.function.Supplier;
@@ -567,6 +573,36 @@ public void run() {
567573
ctx.restore();
568574
whileRunning = true;
569575
in.run();
576+
if (in instanceof RunnableFuture) {
577+
/*
578+
* The wrapped runnable arose from asynchronous submission of a task to an executor. If an uncaught exception was thrown
579+
* during the execution of this task, we need to inspect this runnable and see if it is an error that should be
580+
* propagated to the uncaught exception handler.
581+
*/
582+
try {
583+
((RunnableFuture) in).get();
584+
} catch (final Exception e) {
585+
/*
586+
* In theory, Future#get can only throw a cancellation exception, an interrupted exception, or an execution
587+
* exception. We want to ignore cancellation exceptions, restore the interrupt status on interrupted exceptions, and
588+
* inspect the cause of an execution. We are going to be extra paranoid here though and completely unwrap the
589+
* exception to ensure that there is not a buried error anywhere. We assume that a general exception has been
590+
* handled by the executed task or the task submitter.
591+
*/
592+
assert e instanceof CancellationException
593+
|| e instanceof InterruptedException
594+
|| e instanceof ExecutionException : e;
595+
final Optional<Error> maybeError = ExceptionsHelper.maybeError(e, ESLoggerFactory.getLogger(ThreadContext.class));
596+
if (maybeError.isPresent()) {
597+
// throw this error where it will propagate to the uncaught exception handler
598+
throw maybeError.get();
599+
}
600+
if (e instanceof InterruptedException) {
601+
// restore the interrupt status
602+
Thread.currentThread().interrupt();
603+
}
604+
}
605+
}
570606
whileRunning = false;
571607
} catch (IllegalStateException ex) {
572608
if (whileRunning || threadLocal.closed.get() == false) {
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
/*
2+
* Licensed to Elasticsearch under one or more contributor
3+
* license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright
5+
* ownership. Elasticsearch licenses this file to you under
6+
* the Apache License, Version 2.0 (the "License"); you may
7+
* not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
20+
package org.elasticsearch.threadpool;
21+
22+
import org.elasticsearch.test.ESTestCase;
23+
import org.junit.After;
24+
import org.junit.Before;
25+
26+
import java.util.Optional;
27+
import java.util.concurrent.CountDownLatch;
28+
import java.util.concurrent.atomic.AtomicReference;
29+
import java.util.function.Consumer;
30+
import java.util.function.Supplier;
31+
32+
import static org.hamcrest.Matchers.containsString;
33+
import static org.hamcrest.Matchers.hasToString;
34+
import static org.hamcrest.Matchers.instanceOf;
35+
36+
public class EvilThreadPoolTests extends ESTestCase {
37+
38+
private ThreadPool threadPool;
39+
40+
@Before
41+
public void setUpThreadPool() {
42+
threadPool = new TestThreadPool(EvilThreadPoolTests.class.getName());
43+
}
44+
45+
@After
46+
public void tearDownThreadPool() throws InterruptedException {
47+
terminate(threadPool);
48+
}
49+
50+
public void testExecutionException() throws InterruptedException {
51+
runExecutionExceptionTest(
52+
() -> {
53+
throw new Error("future error");
54+
},
55+
true,
56+
o -> {
57+
assertTrue(o.isPresent());
58+
assertThat(o.get(), instanceOf(Error.class));
59+
assertThat(o.get(), hasToString(containsString("future error")));
60+
});
61+
runExecutionExceptionTest(
62+
() -> {
63+
throw new IllegalStateException("future exception");
64+
},
65+
false,
66+
o -> assertFalse(o.isPresent()));
67+
}
68+
69+
private void runExecutionExceptionTest(
70+
final Runnable runnable,
71+
final boolean expectThrowable,
72+
final Consumer<Optional<Throwable>> consumer) throws InterruptedException {
73+
final AtomicReference<Throwable> throwableReference = new AtomicReference<>();
74+
final Thread.UncaughtExceptionHandler uncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
75+
final CountDownLatch uncaughtExceptionHandlerLatch = new CountDownLatch(1);
76+
77+
try {
78+
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
79+
assertTrue(expectThrowable);
80+
throwableReference.set(e);
81+
uncaughtExceptionHandlerLatch.countDown();
82+
});
83+
84+
final CountDownLatch supplierLatch = new CountDownLatch(1);
85+
86+
threadPool.generic().submit(() -> {
87+
try {
88+
runnable.run();
89+
} finally {
90+
supplierLatch.countDown();
91+
}
92+
});
93+
94+
supplierLatch.await();
95+
96+
if (expectThrowable) {
97+
uncaughtExceptionHandlerLatch.await();
98+
}
99+
consumer.accept(Optional.ofNullable(throwableReference.get()));
100+
} finally {
101+
Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler);
102+
}
103+
}
104+
105+
}

0 commit comments

Comments
 (0)