import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SimpleCounter extends HttpServlet { int count = 0; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType( text/plain ); PrintWriter out = res.getWriter(); count++; out.println( Since loading, this servlet has been accessed + count + times. ); } } The code is simple it just prints and increments the instance variable named count but it shows the power of persistence. When the server loads this servlet, the server creates a single instance to handle every request made of the servlet. That’s why this code can be so simple. The same instance variables exist between invocations and for all invocations. A Simple Synchronized Counter From the servlet-developer’s perspective, each client is another thread that calls the servlet via the service(), doGet(), or doPost()methods, as shown in Figure 3-1.* * Does it seem confusing how one servlet instance can handle multiple requests at the same time? If so, it’s probably because when we picture an executing program we often see object instances performing the work, invoking each other’s methods and so on. But, although this model works for simple cases, it’s not how things actually work. In reality, all real work is done by threads. The object instances are nothing more than data structures manipulated by the threads. Therefore, if there are two threads running, it’s entirely possible that both are using the same object at the same time. Figure 3-1. Many threads, one servlet instance
Note: If you are looking for best hosting provider to host and run your tomcat application check Astra tomcat hosting services