0

I am writing a simple HTTP server where the main thread loops in a ServerSocket.accept loop and passing any incoming sockets to worker threads, which will then process them and send back responses. However, I want to special case a shutdown request that will shut down my whole server. I am having trouble using a worker thread to force the main thread to break out of the accept loop and terminate.

Any pointers?

Jin
  • 6,055
  • 2
  • 39
  • 72

3 Answers3

3

Have you tried interrupting the worker thread with workerThread.interrupt();?

That should make accept throw an InterruptedException, which you can catch, clean up what needs to be cleaned up and exit the worker thread.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • Ah but I want to interrupt the main thread which is stuck in accept call. I have access to all of the worker threads, and I have flags in worker threads to terminate them when necessary. Thanks for the answer though! – Jin Jan 27 '13 at 04:17
2

like mentioned in this thread you can just call close() on the server socket which will lead to an Exception in the accept call.

Community
  • 1
  • 1
cybye
  • 1,171
  • 6
  • 13
  • Ah, dirty but probably cleanest and easiest to handle out of all the possible solutions. Thanks! – Jin Jan 27 '13 at 04:13
2

You probably can come up with 100 hacky ways to do that, but I can see only 2 ways in a properly designed application.

  1. It's a break from processing code.

    while (acceptNextRequest()) {
        // Processing code
        if (shouldExitNow()) {
            break;
        }
        // More processing
    }
    // Proper exiting code
    
  2. Check if it's time to exit before accepting next request:

    while (!shouldExitBeforeNextRequest() && acceptNextRequest()) {
        // Processing code
    }
    // Proper exiting code
    

Both solutions ensure proper closing of all connections, notifications to all application close listeners, etc.

If you do System.exit() from a web application, you will close entire web server application (Tomcat, JBoss or whatever use), which is usually not something you want to do from within your application.

And don't mess with the main thread if you run your application in a container.

ATrubka
  • 3,982
  • 5
  • 33
  • 52
  • Yeah, only problem with checking is that the ServerSocket is already in accept call, so it can't check for the condition statements. System.exit() potentially works.. kinda ugly though haha. Thanks! – Jin Jan 27 '13 at 04:15
  • That's fine. It all depends on the actual exiting code. Actually, web applications are not supposed to be closed, ever. You can log out of a web application, clean its state, but you should never make it unavailable for future requests. – ATrubka Jan 27 '13 at 04:54
  • I'm yet to see user requirements demanding a web application to be exited from. That looks more like a quick hack not to develop it the proper way. – ATrubka Jan 27 '13 at 04:56