I created this blog specially for myself to keep track of all the issues or problems for which I Googled a lot and then found the best possible solution.
Thursday, June 30, 2011
J2EE:SERVLET(How do you make a Servlet thread safe?)
Q : How do you make a Servlet thread safe? What do you need to be concerned about with storing data in Servlet instance fields?
A : A typical (or default) Servlet life cycle creates a single instance of each servlet and creates multiple threads to handle the service() method. The multithreading aids efficiency but the servlet code must be coded in a thread safe manner. The shared resources (e.g. instance variables, utility or helper objects etc) should be appropriately synchronized or should only use variables in a read-only manner. There are situations where synchronizing will not give you the expected results
as shown in the diagram below and to achieve the expected results you should store your values in a user session or store them as a hidden field values. Having large chunks of code in synchronized blocks in your service or doPost() methods can adversely affect performance and makes the code more complex.
Alternatively it is possible to have a single threaded model of a servlet by implementing the marker or null interface javax.servlet.SingleThreadedModel. The container will use one of the following approaches to ensure thread safety:
Instance pooling where container maintains a pool of servlets.
Sequential processing where new requests will wait while the current request is being processed.
Best practice: It is best practice to use multi-threading and stay away from the single threaded model of the servlet unless otherwise there is a compelling reason for it. Shared resources can be synchronized, used in readonly manner, or shared values can be stored in a session, as hidden fields or in database table. The single threaded model can adversely affect performance and hence has been deprecated in the servlet specification 2.4.
As shown in the diagram above, threads share the heap and have their own stack space (i.e. each thread has its own stack). This is how one thread’s invocation of a method (doGet(), doPost()) and its local variables (e.g. int y ) are kept thread safe from other threads. But the heap (e.g. int x ) is not thread-safe and must be synchronized for thread safety or stored in an HTTP session or stored as a hidden field. The variable “CONSTANT” is a read only immutable field since it is marked as final and hence thread-safe.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment