Reputation: 5867
I have a a servlet called Statelessservlet which instantiates a new stafeful object every time. Do I need to provide synchronisation to this stateful object?
Here's the code:
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++;
}
}
As per Brian Grotz JCIP each stafeful object should be synchronised, so Ideally we should synchronise this method?
Upvotes: 2
Views: 95
Reputation: 15965
If each interaction with your server creates a new object and discards it, then it's relatively safe not to have synchronization (there is no shared state between multiple threads accessing the service at the same time).
If, on the other hand, those objects are reused, you must synchronize that method.
Also, if, for instance, your performSomeStatefulOperation
changes state of some shared data, then you should synchronize it, unless you took other steps to guarantee it's thread safety (using locks, for instance).
To sum up, it depends on what you're doing in your method. From what you show, there is no need, if there could be a problem from multiple invocations of that method (because it updates shared state), then you should synchronize it.
Upvotes: 4
Reputation: 135992
No synchronization needed since each thread gets its own instance of StatefulObject which is unreachable to other threads.
Upvotes: 4