0

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();
   }
}
  • If you have an object which is not shared with another thread, you don't have to worry about thread safety. – Peter Lawrey Jan 03 '17 at 12:12
  • It means var1 and var2 of class x shall not be thread-safe if multiple threads are using myServlet doGet method. Am I right? – Waleed Khan Jan 03 '17 at 12:14

2 Answers2

2

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 
     ...
    }
davidxxx
  • 125,838
  • 23
  • 214
  • 215
1

Every time you call new x() you are creating a new and independent instance of x This means every thread has it's own copy and nothing is shared so you don't have to worry about thread safety.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • what is it has to do with new instantiation and thread. Each thread is not going to create new instance of x. – Waleed Khan Jan 03 '17 at 12:35
  • @WaleedKhan when you call `new x()`, **every time** by every thread which runs that line, it creates a `new` instance of `x`. Nothing will stop that happening. – Peter Lawrey Jan 03 '17 at 12:47
  • Is it applies to instantiation inside method? What outside method? – Waleed Khan Jan 03 '17 at 13:03
  • @WaleedKhan like I said, every time `new x()` is run it creates a new object. The local variable is run every time the method is called, the field is initialised only once per object it is in. – Peter Lawrey Jan 03 '17 at 13:05