I am building a small Poker app to work on my java skills. I am creating it in Texas Hold’em format.
Basically I want to maintain the hand state in a servlet that handles my AJAX responses. I am guessing the member variable in a servlet is not safe, whereas the session should be. Could you please explain the correct implementation of this solution?
public class PokerClientResponse extends HttpServlet {
private static Logger LOG = Logger.getLogger(PokerClientResponse.class);
private static final long serialVersionUID = 1L;
private HandState handState = null;
public PokerClientResponse() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//Which is the best way to maintain hand state?
//Get the State from the session, then increment it
HttpSession session = request.getSession();
Object obj = session.getAttribute("handState");
//Advance the Hand State
getHandState().goToNextState();
A servlet instance variable (unless it’s a
ThreadLocalis indeed not safe, because there is only a single servlet instance serving all request made to its mapping.All you need to do is save/load the hand state from the session, which is unique per user conversation1. Remove the hand state instance variable.
Remove the hand state getter. Only deal with hand state inside the request processing call, and pass that hand state to other methods that need it (if any).
Your code would be closer to this:
Although I recommend using a constant for the session attribute key.
1 Which is different from unique per browser window or tab; if you have multiple windows or tabs open, they may be sharing the same session.