I saw a servlet sample code from website , this code is said to be thread unsafe,but I cannot tell why it is thread unsafe and what will happen when I use this code.This code is a servlet code which is used to save each visitor's name.
public class UnsafeGuestbookServlet extends HttpServlet {
private Set visitorSet = new HashSet();
protected void doGet(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException, IOException {
String visitorName = httpServletRequest.getParameter("NAME");
if (visitorName != null)
visitorSet.add(visitorName);
}
}
Peoper say that if I change the code like this:
private Set visitorSet = Collections.synchronizedSet(new HashSet());
thread-unsafe problem will be solved.
I know that if this piece of code is thread unsafe, it must be caused by visitorSet,it is a shared data structure.Since String visitorName is a local variable , every thread will make a copy in its own call stack, right?