I have reviewed a sample of a chat server with Node JS and socket IO at http://ahoj.io/nodejs-and-websocket-simple-chat-tutorial. In that sample a simple history variable was used at server to save chat history data. As the Node Js is single thread every thing works fine. (You can ignore above node JS example if you are not interested in node js :) I will explain it in java below )
Consider below servlet which gets message
String from request and add it to an string. This code could be an example of a Chat Server. It gets user messages from request and all it to a history
String and other clients can read it.
public class ChatServlet implements Servlet {
private static String history = "";
public void service(ServletRequest request, ServletResponse response)
history = history.concat(request.getParameter("message"));
}
}
Theoretically, this code is not thread-safe as it use a global static
variable (How do servlets work? Instantiation, sessions, shared variables and multithreading) .
However, I have tested above code with jMeter with lots of concurrence request and the history string always stores all the messages (So no client message lost or over-written), and nothing went wrong! I have not work with threads so I wonder if I am missing something here ! Is the above code thread-safe and can it be trusted.