Last week, you learned how to create, save, and compile a servlet. This week, you will learn more about working with servlets, such as how to code thread-save servlets. This article, the second of three parts, is excerpted from chapter five of the book Murach's Java Servlets and JSP, written by Andrea Steelman and Joel Murach (Murach; ISBN: 1890774189).
Developing Your Servlet Skills - How to code instance variables (Page 3 of 4 )
Figure 5-7 shows how to code instance variables in a servlet. Since multiple threads access a single instance of a servlet, the instance variables of a servlet are used by all the threads. For that reason, you may need to synchronize the access to some instance variables if there’s a chance that use by two or more threads at the same time could corrupt the data.
The code in this figure shows how to add an instance variable named accessCount to the EmailServlet. To initialize a variable like this, you can code its declaration in the init method. This will ensure that the variable is initialized when the instance of the servlet is first created.
If you shut down the server and restart it, though, the servlet will be destroyed and a new instance of the servlet will be created. As a result, any instance variables will be initialized again. If that’s not what you want, you can write the value of the instance variable to a file so the data isn’t lost when the servlet is destroyed.
In this example, the synchronized and this keywords prevent two threads from running the block of code that updates the accessCount instance variable at the same time. Then, after the thread updates the accessCount variable, its value is stored in a local variable so it can’t be accessed by other threads. Later, this local variable is used by the println method to return the value to the browser. This is similar to the code that you saw in the scriptlet for the JSP in the last chapter.
Code that adds an instance variable to the EmailServlet class
public class EmailServlet extends HttpServlet{
private int accessCount;
public void init() throws ServletException{ accessCount = 0; }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
// missing code
int localCount = 0; synchronized(this){ accessCount++; localCount = accessCount; }