SUBJECT CODE
TYPE THE SUBJECT NAME HERE
UNIT NO 3
SERVER SIDE SCRIPTING
● 3.8 Data Storage Servlets -Concurrency
III V
IT8501
WEB TECHNOLOGY
IT8501
WEB TECHNOLOGY
Data Storage Servlets -Concurrency
IT8501
WEB TECHNOLOGY
Servlet Concurrency
• A Java servlet container or web server is multithreaded and multiple requests to the same servlet
may be executed at the same time.
• As we discussed earlier that one and only one instance of Servlet gets created and for every new
request , Servlet Container spawn a new thread to execute doGet() or doPost() methof of a
servlet.
• By default servlets are not thread safe and it is a responsibility of a servlet developer to take
care of it.
IT8501
WEB TECHNOLOGY
Threads Overview
• A thread is a lightweight process which has its own call stack and accesses shared data of other
threads in the same process (shares heap memory).
• Every thread has its own memory cache.
• When we say that a program is multithreaded, we mean that same instance of an object spawns
multiple threads and process this single instance of code.
• This means that more than one sequential flow of control runs through the same memory block.
Lets take a simple java example
public class Counter
{
int counter=10;
IT8501
WEB TECHNOLOGY
public void doSomething()
{
System.out.println(“Inital Counter = ” + counter);
counter ++;
System.out.println(“Post Increment Counter = ” + counter);
}}
Now we execute two threads Thread1 and Thread2 to execute doSomething() method. So it is
possible that
Thread1 reads the value of counter which is 10
Displays the Inital Counter =10 and increment
Before actually Thread1 increments the counter another Thread1 increments the counter
which changed the value of counter to 11
Now Thread1 has value of counter as 10 which is stale now
T
IT8501
WEB TECHNOLOGY
Write Thread Safe Servlets
There are certain points which we should consider while writing servlets.
•Service() , doGet(), doPost() or to be more generic doXXX() methods should not
update or modify instance variables as instance variables are shared by all threads
of same instance.
• If you have a requirement which requires modification of instance variable then do
it in a synchronized block.
Above two rules are applicable for static variables also because they are also shared.
Below are the approaches to make the thread safe
● Synchronized the block where you are modifying instance or static
variables.(refer below code snipped).
IT8501
WEB TECHNOLOGY
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ThreadSafeServlet extends HttpServlet
{
@override
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
int counter;
{
synchronized (this)
{
//code in this block is thread-safe so update the instance variable
}
//other processing;
}
IT8501
WEB TECHNOLOGY
b) Single Thread Model –Implements SingleThreadModel interface to make
our thread single threaded which means only one thread will execute service()
or doXXX() method at a time. A single-threaded servlet is slower under load
because new requests must wait for a free instance in order to proceed
?
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ThreadSafeServlet extends HttpServlet implements
SingleThreadModel {
int counter;
// no need to synchronize as implemented SingleThreadModel
@override
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
}
IT8501
WEB TECHNOLOGY
Servlet is thread safe, there are a few basic rules of thumb you must follow:
1.Your servlet service() method should not access any member variables, unless these
member variables are thread safe themselves.
2.Your servlet service() should not reassign member variables, as this may affect other
threads executing inside the service() method. If you really, really need to reassign a
member variable, make sure this is done inside a synchronized block.
3.Rule 1 and 2 also counts for static variables.
4.Local variables are always thread safe. Keep in mind though, that the object a local
variable points to, may not be so. If the object was instantiated inside the method, and
never escapes, there will be no problem. On the other hand, a local variable pointing to
some shared object, may still cause problems. Just because you assign a shared object
to a local reference, does not mean that object automatically becomes thread safe.
IT8501
WEB TECHNOLOGY
Here is a diagram which illustrates the servlet concurrency rules / issues mentioned
above. The red boxes represent state (variables) that your servlet's service() method
should be careful about accessing
IT8501
WEB TECHNOLOGY
Other Shared Resources
Of course it is not only the member variables and static variables inside the servlet class itself, that
you need to be careful about accessing. Static variables in any other class which are accessed by
your servlet, must also be thread safe. The same is true for member variables of any shared objects
accessed by your servlet.
Code Example
Here is a code example that shows you some of the rules I have been talking about in this text.
public class SimpleHttpServlet extends HttpServlet { // Not thread safe, static. protected static List
list = new ArrayList();
// Not thread safe
protected Map map = new HashMap(); // Thread safe to access object, not thread safe to reassign
variable. protected Map map = new ConcurrentHashMap(); // Thread safe to access object
(immutable), not thread safe to reassign variable. protected String aString = "a string value";
IT8501
WEB TECHNOLOGY
protected void doGet( HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Not thread safe, unless the singleton is 100% thread safe.
SomeClass.getSomeStaticSingleton();
// Thread safe, locally instantiated, and never escapes method.
Set set = new HashSet();
}
}
IT8501
WEB TECHNOLOGY
Conclusion
● We need to be very careful while writing servlets as “by default servlets are not thread safe”.
● If your servlet does not have any static or member variable then no need to worry and your
servlet is thread safe
● If your servlet just reads the instance variable then your servlet is thread safe.
● If you need to modify the instance or static variables , update it in a synchronized block while
holding a lock on Servlet instance
IT8501
WEB TECHNOLOGY