Search code examples
javathreadpoolhttpserver

Java application with httpServer hangs for 45 seconds before exiting


I have been playing around with Java httpServer class a little bit. When I run my test application it will get to the last line (a println) in main about right a way, but then it sits there for about 45 secs before closing the application. Why does it do that and is there a way to make it so it ends faster? Thanks

public class TestTester
{
    public static void main(String[] args) throws IOException {
        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 8780);
        HttpServer server = HttpServer.create(addr, 0);
        server.createContext("/", new MyHandler());
        server.setExecutor(Executors.newCachedThreadPool());
        server.start();


        URL url = new URL("http://localhost:8780/test");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        InputStreamReader(connection.getInputStream()));

        // print out the response headers
        System.out.println("\nHttp Response Headers");
        for (int i=0; ; i++)
        {
            String headerName = connection.getHeaderFieldKey(i);
            String headerValue = connection.getHeaderField(i);

            if (headerName == null && headerValue == null) {
                // No more headers
                break;
            }
            else if (headerName == null) {
                System.out.println( "    " + headerValue);
            }
            else
                System.out.println( "    " + headerName + ": " + headerValue );
        }
        connection.disconnect();

        server.stop(0);
        System.out.println("Stopped Server.");

    } // end main()
}

class MyHandler implements HttpHandler {

    @Override
    public void handle(HttpExchange exchange) throws IOException
    {
        System.out.println("===Enter MyHandler===");
        System.out.println("Http Request Header:");
        // print out the request methode and url
        System.out.println( "    " + exchange.getRequestMethod() + " "
                + exchange.getRequestURI() + " " + exchange.getProtocol());
        // print out the request headers
        Headers requestHeaders = exchange.getRequestHeaders();
        for (String name : requestHeaders.keySet() )
        {
            List<String> values = requestHeaders.get(name);
            for ( String value : values )
            {
                System.out.println( "    " + name + ": " + value);
            }
        }
        // print out the request body if any
        BufferedReader in = new BufferedReader(new InputStreamReader(exchange.getRequestBody()));
        String sCurrentLine;
        System.out.println( "\nHttp Request Body:");
        if ( ! in.ready() )
            System.out.println( "    No Request Body");
        else
        {
            while ((sCurrentLine = in.readLine()) != null) {
                System.out.println("    " + sCurrentLine);
            }
        }

        // set up and send response
        String requestMethod = exchange.getRequestMethod();
        if (requestMethod.equalsIgnoreCase("GET"))
        {
            Headers responseHeaders = exchange.getResponseHeaders();
            responseHeaders.set("Content-Type", "text/html");
            exchange.sendResponseHeaders(200, 0);

            OutputStream responseBody = exchange.getResponseBody();
            responseBody.write("<!DOCTYPE html><html><body><h1>My Response Header</h1><p>And some sample data.</p></body></html>".getBytes());

            responseBody.close();
        }
        exchange.close();
    } // end public void handle()
} // end class

Solution

  • I did find something that seems to work although I am not sure if it is the correct way to be handling this. This is not extensively tested, but it does make it shutdown faster.

    I replaced:

    server.setExecutor(Executors.newCachedThreadPool());
    

    With:

    ExecutorService excu = Executors.newCachedThreadPool();
    server.setExecutor(excu);
    

    Then just before the server.stop(0); I added excu.shutdown();