I am attempting to run a threaded socket server that handles multiple clients simultaneously. However after I telnet into the server and then exit in a non-graceful way, say by closing the window.
The server crashes and returns System.out.println("Runnable terminating with exception: " + e ); with e being java.Lang.NullPointerException.
My question is how can I simply close the socket and keep the server running even if something goes wrong in handleSession(), so that others can connect?
I am new to exceptions so my understand is still elementary.
publc class ThreadedHandler implements Runnable {
Socket incoming;
BufferedReader in;
PrintWriter out;
SortedTopicList topics;
ThreadedHandler(Socket s) {
incoming = s;
}
public void run() {
try {
handleSession(incoming);
}catch (Exception e) {
System.out.println("Runnable terminating with exception: " + e );
}
}
public void handleSession(Socket client) {
try {
//Code goes here
} catch (IOException e) {
System.err.println(e.getMessage());
} finally {
shutdown();
}
}
public void shutdown() {
try {
in.close();
out.close();
incoming.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
My main method is as follows:
public class MessageBoardServer {
public static void main(String[] args) {
Thread t;
try {
ServerSocket ss = new ServerSocket(118118);
while(true) {
Socket session = ss.accept();
t = new Thread(new ThreadedHandler(session));
t.start();
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
Use Executor, to create thread pool, and delegate thread executing to that pool.
Even if one thread throws an exception, the others will be still active.
You can add “unhandledExceptionHandler” to Executor, where you can log every exceptions.
First Executor usage example from google