[concurrency-interest] Spring DispatcherServlet safe publication question

Jason T. Greene jason.greene at redhat.com
Thu Mar 6 10:43:51 EST 2008

Tim Peierls wrote:
> On Thu, Mar 6, 2008 at 2:58 AM, Dhanji R. Prasanna <dhanji at gmail.com 
> <mailto:dhanji at gmail.com>> wrote:
>     Or is it because the servlet container's startup thread locks
>     (presumably) when going thru init?
> That wouldn't be enough, there would have to be a matching lock around 
> every service call.

Not true. As long as the instance fields are not yet visible (published) 
to other threads, and they are never written to afterwards they are 
effectively immutable.

> Last time I looked, the Servlet spec stopped short of saying that there 
> is a happens-before edge between init() and service(). (The word 
> "before" without the "happens-" prefix doesn't count.) It's possible 
> that this has been tightened up, but my own habit is to be extra 
> cautious, and to synchronize access to (or make volatile) all non-final 
> fields of a servlet.

Since the spec requires init() to be ran only once and complete before 
any service method is called, and since instance fields are only ever 
accessed by service methods, they can be effectively immutable. I do 
agree the spec should make this more clear. I will email the servlet EG 
about that.

> As JCiP 4.5.1 points out, however, sometimes you have to assume, when 
> dealing with ambiguous documentation, that a framework is doing the 
> right thing, because it makes no sense for it to do otherwise. And 
> gazillions of happy Spring users haven't complained yet. :-)

It's funny that you bring this up, because I took a look at the tomcat 
source, and sadly they are using DCL to meet the init() requirements 
(will file a bug on this) :(

if (instance == null) {
   synchronized (this) {
     if (instance == null) {
       try {
         instance = loadServlet();
       } catch (ServletException e) {
         throw e;
       } catch (Throwable e) {
         throw new ServletException(..., e);

So, your suggestion of guarding against broken containers with a 
volatile isn't so bad.

Jason T. Greene
JBoss, a division of Red Hat

More information about the Concurrency-interest mailing list