♠ Posted by Unknown in Adv Java at 07:35
Multithreading into Servlet
The servlet container has a pool of
threads that it will dispatch to handle client requests. It is quite likely
that two clients arriving at the same time could be processing through your
service() at the same time. Therefore the service() method must written in a
thread-safe manner. Any access to common resources will need to be guarded by
using the synchronized keyword.
A thread-safe servlet, like a thread safe
JSP, is one that works correctly even if more than one servlet thread is
running at the same time. To code a thread-safe servlet, you not only have to
synchronize the use of any instance variables that could be corrupted, but also
any methods that could cause problems if they were used by two or more threads at the same time.
There are three different levels to limit
the use of code to a single thread. First, you can synchronize a block of code
by using the synchronized and this keywords. Second, you can synchronize an
entire method. Third, you can use the Single ThreadModel interface to limit the
use of an entire servlet to a single thread.
As you code thread-safe servlets, you
must remember that one thread has to wait while another thread is using a
synchronized block of code, a synchronized method, or a single-thread servlet.
Since that can affect the performance of a Web application, your general goal
should be to synchronize as little code as possible. As a result, synchronizing
a block of code within a methods is best for performance, synchronizing a
method is next best, and coding single-thread servlet should be usually
avoided.
The following simple example puts a
synchronized clause around the thread’s sleep() method. This will block all
other threads until the allotted time (five second) is all used up. When testing
this you should start several browser instances and hit this servlet as quickly
as possible start several browser instances and hit this servlet as quickly as
possible in each one – you’ll see that each one has to wait until its turn
comes up.
Example:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ThreadServlet extends
HttpServlet
{
int
i;
public
void service(HttpServletRequest req, HttpServletResponse res) throws
IOException
{
res.setContentType("text/html");
PrintWriter
out = res.getWriter();
synchronized(this)
{
try
{
Thread.currentThread().sleep(5000);
}catch(InterruptedException
e)
{
System.err.println("Intrrupted");
}
}
out.print("<H1>
Finished " + i++ + "</H1>");
out.close();
}
}
It is also possible to synchronize the
entire servlet by putting the synchronized keyword in front of the service()
method.
0 comments:
Post a Comment