Making the fields volatile also works, as long as you are on Java 5 or above.

For your second question, no you do not need to synchronize each
object. You simply need to establish a "happens-before" relationship
between the publication of the fields and the use of those fields.
This is explained properly in the back of Goetz's book but to
summarise, all operations preceding the release of a monitor (i.e. the
end of a synchronized block) are considered to "happen-before" any
operation following a lock of that monitor (i.e. another synchronized
block on the SAME object). So you can set any number of fields in a
synchronized block and they will all be safely published to whomever
accesses them in a later synchronized block.

Regards,
Neil

On Sat, Mar 21, 2009 at 3: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?
>
>
> 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?
>
> Thanks for the help!
> >
>

--~--~---------~--~----~------------~-------~--~----~
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