struts-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Craig R. McClanahan" <>
Subject Re: Is the struts example itself is multi-thread safe?
Date Thu, 01 Mar 2001 05:40:26 GMT
Maya Muchnik wrote:

> Hi,
> In "A Walking Tour of the Struts App", the author has mentioned that "There is only one
object for each action (URI), so your action objects must be
> multi-thread safe". Is the example itself is multi-thread safe?
> I am asking this, because are several actions here, but not one of them use "synchronized"
> Maybe I am missing something...


Thread-safety is a general term meaning "even if two or more users are calling methods in
my class *simultaneously*, nothing will get messed up.

In the case of Action classes in the example application, they are indeed thread safe.  Why?
 Primarily because they use no instance variables -- only
local variables within the perform() method.

If the example used instance variables, then there would be only one copy of those variables
(because Struts creates only one instance of your Action).
However, local variables appear on the stack for each request thread that is happening simultaneously.
 Any single thread can only see its own copy of
these variables, so there is no possibility for contention.

One place you will see synchronization in the example app is when adding to the pseudo-database.
 Consider what would happen if two users logged on with
the same id, and both proceeded to add a new subscription at exactly the same moment.  You
would have two attempts to modify the database (which,
because it is a servlet context attribute, is visible to all request processing threads),
so you need to synchronize here.

The other place that you commonly need to synchronize is when you are modifying session attributes
(read-only access is generally safe without
locking).  It is surprisingly easy to have multiple requests active at the same time for the
same session -- for example:

* In a framed presentation, the browser will often issue
  requests for more than one frame at the same time, all
  with the same session id.

* Users might open multiple browser windows, which (in
  many circumstances) causes each window to be part
  of the same session.

* The user can submit a long running transaction, press
  STOP (which the server does not know about), and then
  start something else.

> THANKS in advance.
> Maya


View raw message