posted 23 years ago
An instance variable is also often known as a class member variable.
public class MyServlet extends HttpServlet {
int x; //x is a member variable
public void doPost(HttpServletRequest req,
HttpServletResponse res)
{
//...
}
}
When the servlet container creates an instance of MyServlet, then that instance has an instance variable x. Now assume a request comes from a client; the servlet container creates a thread and that thread enters the doPost method of the instance. This thread has access to the variable x. If another request thread enters doPost at the SAME time, it also has access to the same variable x. In other words, instance variables are shared by the threads. If one thread makes a change to x, the other thread will see that same change.
If, on the other hand, x is a method variable:
public class MyServlet extends HttpServlet {
public void doPost(HttpServletRequest req,
HttpServletResponse res)
{
int x = 0;
//...
}
}
then each thread gets ITS OWN copy of x. If one thread makes a change to its copy of x, the other thread does not see this change, and vice versa. Method variables are NOT shared between threads.