Reputation: 413
I've read a lot of about servlets and threadsafe - I know, that "Servlet container loads and instantiates each Servlet only once...". But if I create abstract class extends Servlet, that has a method to process with parameters, is this threadsafe to use in descendant?
I know, that "HttpServletRequests and HttpServletResponses are not shared between different threads, so I don't need to synchronize read- and write access on them..."
public abstract class AbstractService extends HttpServlet {
protected String getNameViaParameter(HttpServletRequest httpServletRequest){
String name = null;
String nameViaParam = httpServletRequest.getParameter("name");
if ((nameViaParam != null) && (!nameViaParam.isEmpty())){
name = nameViaParam;
// ... process with name...
}
// return
return name;
}
}
And specified Servlet:
public class Service extends AbstractService {
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// is this thread-safe ???
String name = getNameViaParameter(req);
doSomething(name);
}
}
Thanks for help.
Upvotes: 0
Views: 192
Reputation: 9914
From the given code, it is thread safe as local variables are thread safe. But if you are using an instance variable, then it is likely to change its state. Then you need to handle synchronization.
Upvotes: 0
Reputation: 1500215
You haven't shown anything in the getNameViaParameter
method that affects any shared state within the servlet, so it should be fine. You won't end up with multiple calls for the same request in different threads, so as long as your method only uses the request, it's fine.
You could make that clearer by making the method static, assuming you don't need to override it in other servlets.
Upvotes: 3