SingleThreadModel Interface:
Here we are going to discuss about SingleThradModel in Servlets. As we
know that servlets are server side components that help us for developing
web application on server side. Servlets are used to process multiple requests
simultaneously.
First lets see what is mutithreadModel :
When we instantiate servlet then instance variable created, as a result it will
be used over multiple client request,hence same
instance is shared across multiple clients.
As single instance is shared by all clients so there are chances that same
instance variable is modified by many clients and hence giving undesirable
result .
To avoid this concurrency, we use SingleThreadModel.
How To make single thread model:
By default servlet is multithreaded . Single Thread Model ensures that
servlet handles only one request at a time.When your class is implemented
SingleThreadModel no two threads run simultaneously in service()
method .
To use SingleThreadModel in servlet you have to implement
SingleThreadModelIntetface. public interface SingleThreadModel.
SingleThreadModel ensures that servlet handle only one request at a time.Every
time a new instance of servlet is
created for each client request.It is also called thread safe.
It is a marker interface which does not have any body.
Single thread model is not used generally as it slow down the performance and
increases overhead as new instance of the servlet is created for each and every
new request.
Let’s take an example for SingleThreadModel in handling database
connection as it is useful here to process one request at one time
Example implementation of SingleThreadModel:
package r4r.servlet; import java.io.*; import java.sql.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class SingleThreadModelExample extends HttpServlet implements SingleThreadModel { Connection conn = null; Statement stmt = null; public void init() throws ServletException { try { // load the driver Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url,userName,password); } catch (Exception e) { }} public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); stmt = conn.createStatement(); updateString = "update Persons set name = 'alok sharma' where id=12" stmt.executeUpdate(updateString1); conn.commit(); } public void destroy() { stmt.close(); conn.close(); }}} |
Note: that SingleThreadModel does not
solve all thread safety issues. For eg, session attributes and static variables
can still be accessed by multiple requests on multiple threads at the same time,
even when SingleThreadModel servlets are used. This is the main reason
due to which SingleThreadModel is deprecated. This interface is deprecated in
Servlet API version 2.4.
We can use Synchronized block and synchronized method to obtain threadsafe
Servlet.