[concurrency-interest] Basic thread safety question: final/volatile/synchronized fields

Joe Bowbeer joe.bowbeer at gmail.com
Fri Dec 22 13:21:12 EST 2006


On 12/22/06, Timo Nentwig <tnentwig at verisign.com> wrote:
> Joe Bowbeer wrote:
> > Objects that are not changed after they are constructed come in two
> > flavors: those that can't be changed (aka immutable) and those that
> > could be changed but aren't (aka "effectively immutable").
> >
> > Safe publication means transmitting the object to another thread by
> > means of a shared lock or volatile (that is, a "happens before"
> > relationship).
> >
> > Passing an object through a thread-safe queue is a common means of
> > safe publication.
>
> Sorry, I'm not sure whether I understood this properly: The "effectively
> mutable" case actually is thread-safe or is explicitly necessary that a
> field is declared final to be thread-safe (and if so why is it)?
>

The effectively immutable case is effectively thread-safe, that is, in
practice :-)

Using "final" lifts the safe-publication requirement for immutable
objects.  The only requirement is correct construction, meaning that
the object's reference hasn't been leaked during construction:

http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight

In general, even thread-safe objects must be safely published.
Immutable objects with final fields are an exception. They go one step
further; they are thread-safe even without safe publication.

--
Joe Bowbeer


More information about the Concurrency-interest mailing list