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
This commit is contained in:
Joao Silva 2019-05-17 13:31:40 +01:00 committed by Phillip Webb
parent c5199322cb
commit 2b33e31a7c
3 changed files with 38 additions and 0 deletions

View File

@ -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) {

View File

@ -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();

View File

@ -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() {