Reputation: 35276
I have a web application, which has Servlet and a static Class accessed through getInstance:
MyServlet extends HttpServet {
protected void doGet(...) {
MyClass.getInstance().doStuff();
}
}
When clients connect to the servlet do they get their own intance of MyClass or the instance of this class is global to all servlets? I mean let say it have a static variable that is set during the doGet method, when other clietns access the the web app, will they get the value of the variable set by other client in this static Class?
EDIT:
Specifically, MyClass
represents a class which access web services, something that is authenticated.
Upvotes: 0
Views: 1089
Reputation: 45576
All code in your web application will have access to the same static variable of MyClass
.
However, it is still bound to play by Java thread model rules.
So, in the absence of synchronization, changing it in doGet
does not mean that other threads will see the new value automatically.
Upvotes: 2
Reputation: 597026
Yes, a static
field value is shared within the classloader. So, if MyClass.getInstance()
returns a static
field of MyClass
, it will be shared by all invocations.
Note that there is only one servlet instance, and multiple threads pass through its doGet(..)
method.
If you need to carry some initialization, you have two options: in .getInstance()
or in the servlet's init()
method.
Upvotes: 2
Reputation: 7569
Depends on the implementation of MyClass. If it is a singleton, then it is only one instance for all the "instantiations" required to doStuff.
Share its code and people will help you.
Upvotes: 1