Hello
I have recently been reading the Java Language Specification (JLS)
concerning threads, locks and the Java memory model
http://java.sun.com/docs/books/jls/second_edition/html/memory.doc.html#30206
and the book excerpt "Synchronization and the Java Memory Model" from
"Concurrent Programming in Java" (Doug Lea):
http://gee.cs.oswego.edu/dl/cpj/jmm.html
I am now very puzzled as to how the threading issues described in these
articles relate to a web application.
The articles state that:
JLS: Each thread has a working memory, in which it may keep copies of the
values of variables from the main memory that is shared between all
threads. Changes to variables made by one thread in its working memory
are only guaranteed to be copied back into main memory when the thread
performs an unlock action on any lock, or the thread terminates. A thread is only
guaranteed to load a
variable from the main memory into its working memory when it performs a
lock action or the first time it accesses the variable.
Doug Lea: "Changes to fields made by one thread are guaranteed to be
visible to other threads only under the following conditions: A writing
thread releases a synchronization lock and a reading thread subsequently
acquires that same synchronization lock."
Could anyone please answer the following questions relating to a web
application:
(1) If I use the Sevlet init() method to initialize some variables in a
web application and then access these variables from a service() method,
must I synchronize the setting of the variables from init() and the
getting of these variables from service() in order to guarantee that the
thread running the service() method can see the changes made to the
variables by the init() method on a different thread? Alternatively is
this looked after in some way by Tomcat to ensure that the servlet
initialization is visible to requests to the servlet.
(2) I have the same question regarding the use of the ServletContext
object: must I synchronize access to all attributes that I set/get in the
ServletContext to guarantee that changes made by one thread are visible to
another?
Thanks for your help.
Mark