public class HomeServlet extends HttpServlet {
private Customer currentCust;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException {
HttpSession session = request.getSession(true);
currentCust = (Customer) session.getAttribute("cust");
currentCust.setLastAccessedTime(new Date( ));
...
}
}
In this code, the currentCust field is obtained
from the HttpSession whenever a client enters the
doGet( ) method. Unfortunately, if another thread
invokes this method an instant later, the
currentCust field will be overwritten before the
first thread is complete. In fact, dozens of threads could enter the
doGet( ) method at roughly the same time,
repeatedly replacing the currentCust reference.
This would lead to complete failure of this servlet.
The easy fix is to make currentCust a local
variable as follows:
public class HomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException {
HttpSession session = request.getSession(true);
Customer currentCust = (Customer) session.getAttribute("cust");
currentCust.setLastAccessedTime(new Date( ));
...
}
}
This fixes our problem because each thread gets its own copy of local
variables in Java. By simply removing the object field and replacing
it with a local variable, this particular threading problem is
resolved.