[concurrency-interest] Protecting sensitive resources

Tim Peierls tim at peierls.net
Wed May 10 09:16:34 EDT 2006

On 5/10/06, Mike Quilleash <mike.quilleash at azuresolutions.com> wrote:
> A couple of questions, your comment about the boolean not needing to be
> volatile is that only when using the standard java synchronized, or does it
> also apply to the Lock method too?  I was having difficulty seeing how the
> lock implementation could figure out what variables need to be synched up so
> maybe for Lock you have to use volatile.

Nope, it applies to Lock implementations, too. From the javadoc class
comment for j.u.c.locks.Lock:
Memory Synchronization

All Lock implementations *must* enforce the same memory synchronization
semantics as provided by the built-in monitor lock:

   - A successful lock operation acts like a successful monitorEnteraction
   - A successful unlock operation acts like a successful monitorExitaction

Unsuccessful locking and unlocking operations, and reentrant
locking/unlocking operations, do not require any memory synchronization

What advantages does making the openSessions field final have?  Is it for
> the JVM to optimise and/or protect the field itself from getting modified,
> just the Set contents.

It's not for optimization. It just makes it slightly easier to reason about
whether the synchronization policy of your class is correctly observed.
Without final, you have to ensure that there is no unguarded access of any
kind (write or read) to the openSessions field itself. With final, you only
have to worry about avoiding unguarded access to the field's contents.

It's a small thing in this case, but it's a good habit to get into when
dealing with larger classes and more complicated synchronization policies:
If you can make a field final without contortions, do so. Sometimes it isn't
possible, as with the setter injection pattern used by frameworks like
Spring, where you should normally use volatile instead.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20060510/6ec9ce9d/attachment-0001.html

More information about the Concurrency-interest mailing list