sebb wrote:
> OK, that makes sense.
>
> However, only objects that are immutable from construction are
> thread-safe without needing some kind of synchronisation.
>
> Passing it to a newly created thread would be OK (Thread.start() is
> synch.), but if it is passed to an existing thread some other means of
> synch. would be needed.

That's one reason why immutability is best designed as a property of a
class, rather than a property of instances.  A good immutable class does
not provide any mutation methods in the first place, so there is never any
question about whether instances can or should be mutated, and there is
never* a synchronization issue.

Where there is use in having both mutable and immutable representations
of the same thing, it is better to use separate classes.  In some cases, it
might be useful for one or both classes to provide a mechanism to create
copies in the form of the other class (example1: hypothetical method
MutableVector3D#createImmutableCopy() : Vector3D) (example2: 
hypothetical constructor MutableVector3D#MutableVector3D(Vector3D)).
Instances can still be used (somewhat) interchangeably if their classes
implement a common interface.


*Caveat: if the constructor does something stupid that makes references
accessible to other threads before the constructor returns, then instances
are not automatically safe from construction.


John



      

Reply via email to