Thread Safety

In a typical scenario, only one copy of any particular servlet or filter is loaded 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 thread-safe. 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 thread-safe. If you are using any third-party libraries or extensions, make sure that those components are also thread-safe. 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.[23] If two servlets try to access the balance at the same time, you might get this sequence of events:

  1. User 1 connects to the servlet to make a $100 withdrawal.

  2. The servlet checks the balance for User 1, finding $120.

  3. User 2 connects to the servlet to make a $50 withdrawal.

  4. The servlet checks the balance for User 2, finding $120.

  5. The servlet debits $100 for User 1, leaving $20.

  6. The servlet debits $50 for User 2, leaving -$30.

  7. 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. While a particular ...

Get Java Enterprise in a Nutshell, Second 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.