How do I ensure that my servlet is 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. 2. Every new client request generates (or allocates) a new thread; that thread calls the service() method of your servlet (which may in turn call doPost(), doGet() and so forth). 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 synchr