The Servlet specification provides that a container will instantiate a single instance of my java.servlet.HttpServlet, and invoke the service methods (doGet()/doPost()) from multiple worker threads.
According to normal threading rules, it is not guaranteed that assignments to instance-level fields in init(ServeltConfig) 'happen before' reads from those same fields by other threads executing doGet(), unless someone arranges for synchronization at some point.
Probably, containers do in fact do some kind of external synchronization to ensure that work done in init() is visible to 'subsequent' threads.
However, does the Servlet spec explicitly guarantee that I'm threadsafe? I couldn't find a guarantee like that just now, although I must admit, I haven't read the spec from end-to-end since Servlet 2.4.
EDIT
For example, since some answerers are getting things mixed up, my question is: what is it about the Servlet spec that says the following class is threadsafe?
@WebServlet (initParams = {@WebInitParam(name="b", value="true")})
public Decider extends HttpServlet {
private boolean b = false;
public void init(ServletConfig config) {
this.b = Boolean.parseBoolean(config.getAttribute("b"));
}
public void doGet(HttpServletRequest req, HttpServletResponse res) {
res.sendRedirect(b ? "/true" ? "/false");
}
}
Certainly, if I were to do:
public static void main(String[] argv) {
HttpServlet s = new Decider();
Thread t1 = new Thread(new Runnable() {
public void run() {
s.init(...);
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
s.doGet(...);
}
});
t1.start();
t2.start();
}
... then I'd have a threading bug. What makes containers necessarily different?
EDIT 2
All the answers asserting that "the container takes care of that" are certainly welcome, but my question is specifically about whether the Servlet spec guarantees that behaviour. To answer the question adequately, you've got to make reference to the Servlet spec. (Any version, I'm cool).