Thread Safety
In a typical scenario, only one copy of any particular servlet
or filter is loaded into the server’s runtime at any given time. Each
servlet might, however, be called upon to deal with multiple requests
at the same time. This means that a servlet needs to be threadsafe. If
a servlet doesn’t use any class variables (that is, any variables with
a scope broader than the service method itself), it is generally
already threadsafe. If you are using any third-party libraries or
extensions, make sure that those components are also threadsafe.
However, a servlet that maintains persistent resources needs to make
sure that nothing untoward happens to those resources. Imagine, for
example, a servlet that maintains a bank balance using an int
in memory.[13] If two servlets try to access the balance at the same
time, you might get this sequence of events:
User 1 connects to the servlet to make a $100 withdrawal.
The servlet checks the balance for User 1, finding $120.
User 2 connects to the servlet to make a $50 withdrawal.
The servlet checks the balance for User 2, finding $120.
The servlet debits $100 for User 1, leaving $20.
The servlet debits $50 for User 2, leaving -$30.
The programmer is fired.
Obviously, this is incorrect behavior, particularly that last bit. We want the servlet to perform the necessary action for User 1, and then deal with User 2 (in this case, by giving him an insufficient funds message). We can do this by surrounding sections of code with synchronized blocks. ...
Get Java Enterprise in a Nutshell, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.