Commit 2b33e31a authored by Joao Silva's avatar Joao Silva Committed by Phillip Webb

Allow Tomcat be destroyed regardless of exceptions

Update `TomcatWebServer` so that lifecycle exceptions are silently
swallowed when attempting shutdown. Prior to this commit it was
possible that a Tomcat instance might not be properly destroyed and
could leave non daemon threads running, which prevent the JVM from
exiting.

Fixes gh-16892
parent c5199322
......@@ -122,6 +122,7 @@ public class TomcatWebServer implements WebServer {
}
catch (Exception ex) {
stopSilently();
destroySilently();
throw new WebServerException("Unable to start embedded Tomcat", ex);
}
}
......@@ -242,6 +243,15 @@ public class TomcatWebServer implements WebServer {
}
}
private void destroySilently() {
try {
this.tomcat.destroy();
}
catch (LifecycleException ex) {
// Ignore
}
}
private void stopTomcat() throws LifecycleException {
if (Thread.currentThread()
.getContextClassLoader() instanceof TomcatEmbeddedWebappClassLoader) {
......
......@@ -523,6 +523,25 @@ public class TomcatServletWebServerFactoryTests
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
public void exceptionThrownOnContextListenerDestroysServer() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0) {
@Override
protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
try {
return super.getTomcatWebServer(tomcat);
}
finally {
assertThat(tomcat.getServer().getState())
.isEqualTo(LifecycleState.DESTROYED);
}
}
};
assertThatExceptionOfType(WebServerException.class)
.isThrownBy(() -> factory.getWebServer((context) -> context
.addListener(new FailingServletContextListener())));
}
@Override
protected JspServlet getJspServlet() throws ServletException {
Tomcat tomcat = ((TomcatWebServer) this.webServer).getTomcat();
......
......@@ -1401,6 +1401,15 @@ public abstract class AbstractServletWebServerFactoryTests {
}
public static class FailingServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
throw new FailingServletException();
}
}
private static class FailingServletException extends RuntimeException {
FailingServletException() {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment