我有一个名为 Statelessservlet 的 servlet,它每次都会实例化一个新的 stafeful 对象。我需要为这个有状态对象提供同步吗?
这是代码:
public class StatelessServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
StatefulObject stObj = new StatefulObject(Integer.parseInt(req.getParameter("id")));
stObj.performSomeStatefulOperation();
...
}
}
class StatefulObject {
private int id;
public StatefulObject(int id) {
this.id = id;
}
//Is synchronized really needed here???
public synchronized void performSomeStatefulOperation() {
id++;
}
}
根据 Brian Grotz JCIP,每个 stafeful 对象都应该同步,所以理想情况下我们应该同步这个方法?