Why is my java program spinning after I hit server.stop(0)?

396 views Asked by At

I wrote a basic java server class. When it handles the "shutdown" request, it calls server.stop(0) and the spins in place. Why is this happening?

I copied most of the code from this StackOverflow post. The only significant modification to this code is that I added the server.stop(0).

Other facts: I am running this using java 8 and I am running this through IntelliJ.

package good.question.ask.questions.stackoverflow;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

public class ServerTester2
{
    private HttpServer server = null;
    public static void main(String[] args) throws Exception {
    ServerTester2 serverTester2 = new ServerTester2();
    serverTester2.start();
}
void start()
{
    try {
        server = HttpServer.create(new InetSocketAddress(8000), 0);
    } catch (IOException e) {
        e.printStackTrace();
    }
    server.createContext("/shutdown", new MyHandler());
    server.setExecutor(null); // creates a default executor
    server.start();
}

class MyHandler implements HttpHandler
{
    @Override
    public void handle(HttpExchange t) throws IOException
    {
        String response = "This is the response";
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
        t.close();
        System.out.println("Stopping Server...");
        stop();
        System.out.println("Server Stopped!");
    }
}

void stop()
{
    server.stop(0);
}
}

Currently, the server returns a response message to the client (I tested that using postman), and then prints "Stopping Server" to the console. After that, the server object seems to be shut down, because when I send it more requests it doesn't respond to them, however, the thread running the server continues to spin.

Minimally, I expected the server to reach this line of code

System.out.println("Server Stopped!"); 

but it never does.

More to the point, I expected the server thread to terminate but instead, it just spins.

Why is this happening? (Do I have a deadlock in the code somewhere?) Is there a better way to handle server shutdown (using the httpserver library)?

0

There are 0 answers