Search code examples
javaserversocket

Creating a server, techniques to keep a service running (or blocked?)


When creating a standalone server in Java (not using a container like tomcat/jetty), what are the various techniques to keep the service running and not ending?

I have seen where people use a ServerSocket (since you will be communicating with the service presumably), and they use ServerSocket.accept() which blocks until it receives a message. And this is usually done in a while loop:

while(...) {
   serverSocket.accept();
}

(http://docs.oracle.com/javase/6/docs/api/java/net/ServerSocket.html#accept())

Is this the only way? If not, what other ways are there and any pros/cons with it?

Are there any libraries that help with building your own service, or its pretty much roll your own.


Solution

  • There are various libraries that help you roll your own Windows/Unix service in Java:

    How you keep the application running depends on the actual needs of your application. If your application is a server, you would normally want to listen for incoming connections which usually involves some sort of blocking/polling. How you do that again depends on the type of server you want to build. Of the generic solutions there's the ServerSocket class and its method accept() that you already mentioned. Another possibility is to use java.nio and implement a reactor which provides a single-threaded server that can handle multiple connections at once (see http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf for details), but may be a bit hard to grasp and debug.