How do I ensure that my servlet is thread-safe?

Alex Chaffee



[See also What is the meaning of calling a method or object "thread-safe?" ]

This is actually a very complex issue. A few guidelines:

  1. The init() method is guaranteed to be called once per servlet instance, when the servlet is loaded. You don't have to worry about thread safety inside this method, since it is only called by a single thread, and the web server will wait until that thread exits before sending any more threads into your service() method.


  3. Under most circumstances, there is only one instance of your servlet, no matter how many client requests are in process. That means that at any given moment, there may be many threads running inside the service() method of your solo instance, all sharing the same instance data and potentially stepping on each other's toes. This means that you should be careful to synchronize access to shared data (instance variables) using the synchronized keyword.


  4. Note that you need not (and should not) synchronize on local data or parameters. And especially you shouldn't synchronize the service() method! (Or doPost(), doGet() et al.)

  5. A simple solution to synchronizing is to always synchronize on the servlet instance itself using &amp;quot;synchronized (this) { ... }&amp;quot;. However, this can lead to performance bottlenecks; you're usually better off synchronizing on the data objects themselves.

  6. If you absolutely can't deal with synchronizing, you can declare that your servlet &amp;quot;implements SingleThreadModel&amp;quot;. This empty interface tells the web server to only send one client request at a time into your servlet. From the JavaDoc: &amp;quot;If the target servlet is flagged with this interface, the servlet programmer is guaranteed that no two threads will execute concurrently the service method of that servlet. This guarantee is ensured by maintaining a pool of servlet instances for each such servlet, and dispatching each service call to a free servlet. In essence, if the servlet implements this interface, the servlet will be thread safe.&amp;quot; Note that this is not an ideal solution, since performance may suffer (depending on the size of the instance pool), plus it's more difficult to share data across instances than within a single instance.

    See also What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?



  9. destroy() can not throw an exception, so if something bad happens, call log() with a helpful message (like the exception). See the &amp;quot;closing a JDBC connection&amp;quot; example in Sun's Tutorial.


0 Comments  (click to add your comment)
Comment and Contribute









About | Sitemap | Contact