问题
Is it necessary to mark all the servlet instance variables as "volatile" (or to access them from within synchronized sections)? Including those defined in the "init" method, and not modified afterwards?
I understand that the "init" method is called by one thread, and the variable will be accessed by another thread, so it seems to be necessary. Or maybe not? Is there any mechanism that guarantees that the current values of instance variables will be visible to all the other threads when the "init" method is finished?
回答1:
The servlet container will make sure there is a memory barrier between the initialization of the servlets and their invocations. You shouldn't have to do anything.
Note: I haven't found such a requirement in the spec, but I would consider it a failure of the container not to do it. BTW, in GenericServlet, the instance variable ServletConfig config initialized by the init method is not marked as volatile.
来源:https://stackoverflow.com/questions/11719916/marking-servlet-instance-variables-defined-in-init-as-volatile