Search code examples
javaspringspring-boot

Can't terminate a Spring Boot job application with SpringApplication.exit() due to Tomcat error "Socket accept failed"


I have a job application (to be run as an outside cron in EKS, not a cron within this Spring Boot app itself) which needs to terminate. I run it in Eclipse as Application.java -> Run, and when it's done, it does not terminate (similar to a Web app).

But when I do this manually at the end of my run():

@SpringBootApplication
public class MyApplication implements CommandLineRunner {

    @Autowired
    private ApplicationContext appContext;

    @Override
    public void run(String... args) throws Exception {

            // ... Run job, and at the end terminate manually

            SpringApplication.exit(appContext, new ExitCodeGenerator() {

                @Override
                public int getExitCode() {
                    return 0;
                }
                
            });

I get this error:

org.apache.tomcat.util.net.Acceptor.log(175) - Socket accept failed

023-03-24 11:27:29.364 [main] INFO  o.a.coyote.http11.Http11NioProtocol.log(173) - Pausing ProtocolHandler ["http-nio-8081"]
2023-03-24 11:27:29.364 [main] WARN  o.apache.tomcat.util.net.NioEndpoint.log(173) - Failed to unlock acceptor for [http-nio-8081] because the local address was not available
2023-03-24 11:27:29.364 [main] INFO  o.a.catalina.core.StandardService.log(173) - Stopping service [Tomcat]
2023-03-24 11:27:29.364 [http-nio-8081-Acceptor] ERROR org.apache.tomcat.util.net.Acceptor.log(175) - Socket accept failed
java.nio.channels.AsynchronousCloseException: null
    at java.base/java.nio.channels.spi.AbstractInterruptibleChannel.end(AbstractInterruptibleChannel.java:202)
    at java.base/sun.nio.ch.ServerSocketChannelImpl.end(ServerSocketChannelImpl.java:376)
    at java.base/sun.nio.ch.ServerSocketChannelImpl.accept(ServerSocketChannelImpl.java:399)
    at org.apache.tomcat.util.net.NioEndpoint.serverSocketAccept(NioEndpoint.java:520)
    at org.apache.tomcat.util.net.NioEndpoint.serverSocketAccept(NioEndpoint.java:79)
    at org.apache.tomcat.util.net.Acceptor.run(Acceptor.java:128)
    at java.base/java.lang.Thread.run(Thread.java:833)

Is there a way to remove the Tomcat layer from this Spring Boot job app and have it terminate manually?


Solution

  • I found the solution: just remove from Pom.xml the spring-boot-starter-web dependency, per this thread.

        <!--  Removed 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        -->
    

    This automatically removes the embedded Tomcat. In fact, I don't even need to do SpringApplication.exit() anymore, I got rid of that extra code. Now the job immediately terminates on completion.