Servlet instances are container-aggregated. Thus, any number of Servlet objects can be shared by any number of threads in a real-world scenario. All doXXX () methods and other methods called from them will be separated by Threads.
Therefore, it is highly discouraged to have class level variables (to maintain state) in Servlets. Although you probably have constants, static helper methods, and static variables that are shared by instances and are not constantly changed by clients using Servlet.
Although things are discouraged, it doesnโt stop you from synchronizing variables / methods. This would ensure that only one thread accesses the resource at a time, but there will be a penalty for performance, as threads may need others to release the resource first before taking up the lock.
But there is a better way. If you want to save state with a servlet and want to save variables to one client, your Servlet should implement javax.servlet.SingleThreadModel . If your servlet implements this token interface, the container will know that it maintains state, and therefore only one thread will be serviced per instance.
source share