1

Suppose I have a static method in a class like so:

public static String getSomething(HttpServletRequest request)

Which, in the method, calls request.getHeader("headerName") and request.getParameter("parameterName").

Also, In a Struts 2 Action , I make a call to this function within execute():

private String theString;

public String execute() throws Exception {
    theString = TheClass.getSomething(ServletActionContext.getRequest());
    ....
    ....
}

Assuming I make no modifications to the request objection in my static getSomething(request) function, is this thread safe? I'm guessing yes, since from what I understand the HttpServletRequest object in an action is thread local, but I'm not 100% sure.

jtyler
  • 1,055
  • 2
  • 15
  • 22
  • Each thread has a separate thread, so it doesn't matter if it's called from multiple threads as they share no state. – Jimadilo Dec 03 '12 at 21:41
  • @Jimadilo: But I guess we have only one action class object (Singleton, this is my assumption based on Servlet principle). So, all threads (requests from browser) will manipulate same object state (theString) in this case, isn't it? – kosa Dec 03 '12 at 21:44
  • @Nambari No. Struts 2 instantiates an action per request. Servlets aren't Struts 2. – Dave Newton Dec 03 '12 at 22:01
  • @DaveNewton: Thanks for that clarification, as I said haven't worked on Struts2. I will remove my first comment. – kosa Dec 03 '12 at 22:12

2 Answers2

0

Yes, it's totally thread safe as all the variables are only referenced from the stack.

Jimadilo
  • 497
  • 3
  • 10
  • So there's no chance that Struts 2 would make any changes to the HttpServletRequest object in another thread, since it's thread-local? – jtyler Dec 03 '12 at 21:56
  • @jtyler A request is per-request, otherwise it's not the request being processed. – Dave Newton Dec 03 '12 at 22:02
  • Excellent, OK, I wasn't sure if there might be anything weird that Struts 2 might be doing with the request that I wasn't aware of - Thank you. – jtyler Dec 03 '12 at 22:04
0

Yes its thread safe, since you are passing this as a parameter. Its like using a static Math class in your code.

CodeDreamer
  • 444
  • 2
  • 8