Marking servlet instance variables defined in “init” as “volatile”

有些话、适合烂在心里 提交于 2019-12-30 09:51:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!