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;
}
// missing code
out.println(
// missing code
+ "<i>This page has been accessed " + localCount + " times.</i>"
// missing code
);
}
}
Description
- An instance variable of a servlet belongs to the one instance of the servlet and is shared by any threads that request the servlet.
- You can initialize an instance variable in the init method.
- If you don’t want two or more threads to modify an instance variable at the same time, you must synchronize the access to the instance variables.
- To synchronize access to a block of code, you can use the synchronized keyword and the this keyword.
Figure 5-7 How to code instance variables
Next: How to code thread-safe servlets >>
More Java Articles
More By Murach Publishing
|
This article is excerpted from chapter five of the book Murach's Java Servlets and JSP, written by Andrea Steelman and Joel Murach (Murach; ISBN: 1890774189). Check it out today at your favorite bookstore. Buy this book now.
|
|