Blog

Graceful shutdown on Embedded Jetty

You should set following 2 options.

    server.setStopAtShutdown(true);
    server.setStopTimeout(7_000);

setStopAtShutdown sets code Runtime.getRuntime().addShutdownHook to stop Jetty at JVM shutdown phase.

ref. https://github.com/eclipse/jetty.project/blob/master/jetty-util/src/main/java/org/eclipse/jetty/util/thread/ShutdownThread.java

setStopTimeout is required. Without this option, Jetty kills all connections ASAP.

See following code.

    // Shall we gracefully wait for zero connections?
    long stopTimeout = getStopTimeout();
    if (stopTimeout>0)
    {
        long stop_by=System.currentTimeMillis()+stopTimeout;
        if (LOG.isDebugEnabled())
            LOG.debug("Graceful shutdown {} by ",this,new Date(stop_by));

        // Wait for shutdowns
        for (Future<Void> future: futures)
        {
            try
            {
                if (!future.isDone())
                    future.get(Math.max(1L,stop_by-System.currentTimeMillis()),TimeUnit.MILLISECONDS);
            }
            catch (Exception e)
            {
                mex.add(e);
            }
        }
    }

https://github.com/eclipse/jetty.project/blob/master/jetty-server/src/main/java/org/eclipse/jetty/server/Server.java#L432-L453