Going back to the beginning here, I don't think that objects of this class
are thread-safe. Because the field obj is not final, and there's no synchronization or use of volatile, there's no guarantee that the value set for obj in the constructor will be seen by all other threads, even after the constructor completes. It's possible for another thread to get a reference to this object and see obj == null. Strange, but true.
JLS 17.5 shows a similar example in which the final field x is guaranteed to have been initialized, but the non-final field y is not. Fundamentally, this class is
not thread=safe.
However, it's unlikely that the
SCJP exam will ask questions related to exact understanding of the
Java memory model. So you could probably skip this if you like.
[Anupam Sinha]: What is Objects of this class. It's instances or it's instance variables? "Objects of this class" means "instances of this class". Same thing.
[Anupam Sinha]: If it's instances would it be wise enough to say the class is thread safe but it's instance variables are not. Well I think the class is
not thread safe because the instance variable obj is not adequately protected. But aside from that, I think it would be more accurate to say that the objects
referenced by the instance variable are not necessarily thread-safe. The variable itself is almost thread-safe; it would be completely thread-safe if it had been declared final. But the object it points to... we don't know anything at all about that, so it should be assumed to be not thread-safe.
[ May 20, 2007: Message edited by: Jim Yingst ]