java - Is synchronisation needed here? -
i have a servlet called statelessservlet instantiates new stafeful object every time. need provide synchronisation stateful object?
here's 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 needed here??? public synchronized void performsomestatefuloperation() { id++; } }
as per brian grotz jcip each stafeful object should synchronised, ideally should synchronise method?
if each interaction server creates new object , discards it, it's relatively safe not have synchronization (there no shared state between multiple threads accessing service @ same time).
if, on other hand, objects reused, must synchronize method.
also, if, instance, performsomestatefuloperation
changes state of shared data, should synchronize it, unless took other steps guarantee it's thread safety (using locks, instance).
to sum up, depends on you're doing in method. show, there no need, if there problem multiple invocations of method (because updates shared state), should synchronize it.
Comments
Post a Comment