- Java EE Tutorials
- Servlets Tutorials
- Servlets Interview Questions
The SingleThreadModel interface was designed to guarantee that only one thread is executed at a time in a given servlet instance’s service method. It is a marker interface and has no methods.
This interface is currently deprecated, excerpts from the Java Doc:
Deprecated. As of Java Servlet API 2.4, with no direct replacement. It is recommended that a developer take other means to resolve those issues instead of implementing this interface, such as avoiding the usage of an instance variable or synchronizing the block of the code accessing those resources. The SingleThreadModel Interface is deprecated in this version of the specification.
Let us see a simple example using this interface, though it doesn’t guarantee what its specification says.
Example of SingleThreadModel
package javabeat.net.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.SingleThreadModel; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SingleThreadModelExample extends HttpServlet implements SingleThreadModel { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print("Welcome"); try { Thread.sleep(2000); out.print(" to Javabeat"); } catch (Exception e) { } out.close(); } }
Web.xml
<web-app> <servlet> <servlet-name>SingleThreadModelExample</servlet-name> <servlet-class>javabeat.net.SingleThreadModelExample </servlet-class> </servlet> <servlet-mapping> <servlet-name>SingleThreadModelExample</servlet-name> <url-pattern>/SingleThreadModelExample</url-pattern> </servlet-mapping> </web-app>
Example Explanation
- Class SingleThreadModelExample implements the SingleThreadmodel interface. The class SingleThreadModelExample which is a servlet prevents handling Single requests at a single time.
- Here sleep() is a static method in Thread class, which is used to suspend execution of a thread for some specified milliseconds. Thread. Sleep( 2000 ) will stop the execution of the thread for 2000 millisecond.
- When another user access the same servlet, the new instance is created instead of using the same instance for multiple threads.
Previous Tutorial : MVC Architecture || Next Tutorial : HTTP Codes