Menu

#191 Instance variables in a Servlet class

Long-term
closed
rules (229)
5
2012-10-07
2003-11-16
No

I would like to see a rule that flags any member variable
declarations in a servlet class.

For example...

Suppose that I have two classes, Bar and FooServlet

public class Bar
{
private HttpServletRequest request;

// ...

public HttpServletRequest getHttpServletRequest()
{
// ...
}
}

public class FooServlet extends
javax.servlet.http.HttpServlet
{
private Bar b;

// ...
}

The servlet class, FooServlet, is not thread-safe.
Threads can modify the variable "b".

Generally speaking, it is a bad idea to use instance
variables in
a servlet class.

References:

1) http://www.jguru.com/faq/view.jsp?EID=150

2) Java Servlet 2.2 specification:

{{

Multithreading Issues

During the course of servicing requests from clients, a
servlet
container may send multiple requests from multiple
clients through the
service method of the servlet at any one time. This
means that
the Developer must take care to make sure that the
servlet is properly
programmed for concurrency.

If a Developer wants to prevent this default behavior, he
can program
the servlet to implement the SingleThreadModel
interface. Implementing
this interface will guarantee that only one request
thread at a time
will be allowed in the service method. A servlet container
may satisfy
this guarantee by serializing requests on a servlet or by
maintaining a
pool of servlet instances. If the servlet is part of an
application that
has been marked as distributable, the container may
maintain a pool of
servlet instances in each VM that the application is
distributed across.
If a Developer defines a service method (or methods
such as doGet or
doPost which are dispatched to from the service method
of the
HttpServlet abstract class) with the synchronized
keyword, the servlet
container will, by necessity of the underlying Java
runtime, serialize
requests through it. However, the container must not
create an instance
pool as it does for servlets that implement the
SingleThreadModel. It is
strongly recommended that developers not synchronize
the service method
or any of the HttpServlet service methods such as
doGet, doPost, etc.

}}

Discussion

  • Tom Copeland

    Tom Copeland - 2003-11-17

    Logged In: YES
    user_id=5159

    Good one. It'd probably be worth starting a new ruleset -
    servlets.xml.

    Yours,

    Tom

     
  • Tom Copeland

    Tom Copeland - 2003-11-24

    Logged In: YES
    user_id=5159

    Here ya go:

    //UnmodifiedClassDeclaration[@ExplicitExtends='true']/Name[@Image='HttpServlet']

    Note that this will only work with the currently code in CVS
    due to the use of the new "ExplicitExtends" thing; you can
    download a new pmd-1.3.jar file here:

    http://infoether.com/~tom/pmd-1.3.jar

    that contains this fix.

    Thanks,

    Tom

     

Log in to post a comment.

MongoDB Logo MongoDB