Issue
Are instance variables of non-servlet classes are thread safe if instantiated inside servlet method like below??
//Non-servlet Class
public class x{
public String var1;
public String var2;
public String method(){
return (var1 + var2);
}
}
Servlet Class
public class myServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String varA = "Hello ";
String varB = "World";
String varC = null;
x xx = new x();
xx.var1 = varA;
xx.var2 = varB;
varC = xx.method();
}
}
Solution
Are instance variables of non-servlet classes are thread safe?
In your case, it is not an instance variable but a locale variable in the execution scope of the doGet()
method.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
...
x xx = new x();
...
}
Locale variables declared and used in a method are isolated between the calls to it of multiple threads. So you have no potential concurrency here.
If you xx
variable was a instance variable, you would have a race condition since multiple threads could access them in a concurrent way if the servlet was called multiple times in a close timing.
public class myServlet extends HttpServlet {
x xx = new x();
...
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
...
xx.doSomething(); // concurrency race
xx.var1 = varA; // concurrency race
...
}
Answered By - davidxxx