Singlethreadmodel in servlet in java

Also covers that why programmers are discouraged from using this interface? Let us see first what happens when a servlet is not implemented with this interface.

The container creates only single instance of a servlet and sends multiple service requests with different threads to the instance.

This leads to thread unsafe of the servlet due to instance variables declared in it are shared between multiple threads simultaneously. To make the servelet thread-safe , the implementation of the service() method should be thread-safe.

One ways is to implement the it by the marker interface called Single Thread Model.

By instead implementing and having one "connection" instance variable per servlet, a servlet can easily handle concurrent requests by letting its server manage the servlet instance pool (which doubles as a connection pool). import *; import *; import *; import javax.servlet.*; import javax.*; public class Single Thread Connection extends Http Servlet implements Single Thread Model { Connection con = null; // database connection, one per pooled servlet instance public void init(Servlet Config config) throws Servlet Exception { super.init(config); // Establish the connection for this instance con = establish Connection(); Auto Commit(false); } public void do Get(Http Servlet Request req, Http Servlet Response res) throws Servlet Exception, IOException { Content Type("text/plain"); Print Writer out = Writer(); // Use the connection uniquely assigned to this instance Statement stmt = con.create Statement(); // Update the database any number of ways // Commit the transaction con.commit(); } public void destroy() { if (con !

= null) con.close(); } private Connection establish Connection() { // Not implemented.

Thus, any servlet implementing Such a life cycle is pointless for a counter or other servlet application that requires central state maintenance.

The life cycle can be useful, however, in avoiding synchronization while still performing efficient request handling.

Bemerkungen