users@glassfish.java.net

Re: Container injected _at_Resource fields should be declared "volatile"?

From: <glassfish_at_javadesktop.org>
Date: Fri, 16 Nov 2007 11:53:13 PST

Injection code is evil in some ways; one can't easily use 'final' for example to both guarantee and document immutability; it's a guessing game.

In the absence of specific guarantees, fields should be marked 'volatile'. It has nothing to do with the container per se, only with the "happens before" clause upon which the JVM memory model rests.

To safely not mark a variable 'volatile', the following conditions must hold:
- the variable must be set once and only once (barring other synchronization efforts);
- injecting the variable must "happen before" (JVM memory model term) the variable is read by the consuming thread.

If the variable is changed more than once, then the same "happens before" guarantee must be in place. There are many things that guarantee this: 'synchronized' on a shared lock, certain operations on threads, reads of a shared 'volatile' variable, etc.

Behavior might be poorly or inaccurately documented, and threading is hard to get right, even by experienced developers. With those risks in mind, using 'volatile' is highly prudent if there is any doubt as to the way in which the variable is injected and/or how many threads might access it. Use of 'volatile' is highly efficient, and injected variables probably are not used in tight loops anyway. Better safe than sporadically sorry.
[Message sent by forum member 'llc' (llc)]

http://forums.java.net/jive/thread.jspa?messageID=245859