Just Sharing Thoughts…

A vision without skill is like a day dreaming…

Thread-safety issue in Servlets

Posted by Vijay Kumar on September 23, 2008

Generally, the thread-safety issue breaks down like this:

Local variables:
thread-safe in any context, servlet or otherwise

Instance variables:
not normally thread-safe, thread safe in servlets implementing the
SingleThreadedModel.  But since as Corey mentions, most containers will
create multiple copies of your servlet (each with it’s own copy of the
instance variables) as simultaneous requests come in, instance variables
become essentially useless for sharing data outside the scope of a single
method call (the main reason they are used in servlets).

Static variables:
not thread-safe.  Even the SingleThreadedModel does not help, since most
containers will again create several copies of your servlet to guarantee
acceptable performance, and those copies will all share the same static
variables associated with the servlet’s class, you must manually synchronize
access to them to be thread-safe.

Request scope attributes:
thread-safe by default, the container handles each request with a single
worker thread, even when it’s forwarded or included, the RequestDispatcher
interface takes care of marshalling the Request object safely.  You have to
do strange things, like passing the request object out to an external
object, to be at risk here.

Session scope attributes:
not thread-safe.  The user can open multiple browser windows, which under
some configurations will all share the same cookies (thus the same
HttpSession object on the server).  Your page may also use frames, leading
to the same problem.  Or impatient users may hit the refresh button on your
page, again same problem.  Multiple accesses by simultaneous requests to the
same HttpSession object.

Context scope attributes:
not thread safe.  All servlets in the webapp share these, so they’re clearly
at risk of frequent multi-threaded access.

access to any sort of common resource (like an open socket, a file on the
hard disk, etc.):
not thread-safe.  Multiple requests coming in for any servlet that accesses
them can generate concurrent access.

Advertisements

2 Responses to “Thread-safety issue in Servlets”

  1. Sanjay Kumar said

    Nice information!!!!!1

  2. to Ty? ;Pnwchodzu0105c na Twego bloga za kau017cdym razem u017cau0142uje ze nie wypowiadam sie na temat, ale niestety nie znam sie na sztuce , j Click http://d2.ae/hool09070

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: