On Sat, Mar 21, 2009 at 4:10 PM, Brian Frank <[email protected]> wrote:
>
> Suppose I have an immutable class, but I can't actually make all my
> fields final.  What is the next best way to safely publish that class
> to other threads.  Is it simply something like this at the end of my
> constructor:
>
>  synchronized (this) {}
>
> Is there anything more efficient?

It's a bit more complex than just what happens in the constructor. In
order to safely publish an object, you need to be sure that it is
properly constructed: the 'this' reference must not escape during
construction, ie. by being pased as a parameter to somewhere else that
might expect the object to be fully constructed.

Once you have a properly constructed object, you can start talking
about publishing it safely, and there are several ways that such an
object can be safely published:
 * it's initialized from a static initializer: static { classVar = new
Object() }
 * it's reference is written to a volatile variable or an AtomicReference.
 * it's stored in a final field of another prop. constructed object.
 * it's stored in a field that is properly guarded by a lock.
 * it's stored in any other data-structure or parsed to any other
method that guarentees safe publication, like a ConcurrentHashMap.

So you see, if you cannot have all of your fields be final, then safe
publication is out of the hands of your constructor, an have to rely
on how you share references to this object with other threads.

>
>
> Another point I am a bit confused about is how safe publishing works
> with a tree or graph of objects.  Suppose I have a linked list of
> objects such as:
>
>  a -> b -> c -> d
>
> If I wish to safely publish that data structure to other threads, do I
> only need to synchronize "a"?  Or do I actually have to synchronize on
> each object I might access in another thread?

As long as all of the references are written by a single thread and
*before* the presumably safe publication of 'a', then 'b', 'c' and 'c'
will also be safely published.

>
> Thanks for the help!
> >
>



-- 
Venlig hilsen / Kind regards,
Christian Vest Hansen.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "JVM 
Languages" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/jvm-languages?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to