[concurrency-interest] synchronized on construction
jmanson at cs.purdue.edu
Tue May 23 15:40:55 EDT 2006
Jason Mehrens wrote:
> Browsing over the java.util.Vector class I noticed that in the constructors,
> the initial writes to the internal data members (non-final and non-volatile)
> are not performed under a synchronized block. The same is true for when a
> Vector is deserialized. Where does happens-before edge occur so that other
> threads don't see uninitialized values of the internals? The only happens
> before-edges I can think of are during handoff between threads or on the
> call to Thread.start(). Is how this class conforms to the JMM or is
> something else going on?
Well, bear in mind that only one thread has access to instances of these
classes during construction. JMM problems only come up here if you pass
a reference to the object to another thread via a data race. These
classes are not designed to work correctly if you do that - only the
immutable ones, like String, really are.
If you are using this class, it is therefore imperative to provide
proper synchronization during a handoff.
This is one of the reasons why people have moved away from Vector and
Hashtable -- by claiming that they are thread-safe, they make people
stop worrying about multithreaded behavior. However, their guarantees
are illusory - if you examine them too closely, they melt away...
More information about the Concurrency-interest