ObjectWrapper would be thread safe if "obj" were immutable. If "obj" is mutable two threads could end up with a shared reference "obj" pointing to the same object. In that case, one could modify the state of the object, and the other should have to deal with an object that has changed of state "magically". I mean, without its control and at any time. ______________________________________________
Now, assuming Content class implements properly the clone() method, and that Content objects are mutable. Are the following classes thread safe ?
warning clone method is not on the exam but it is related to thread safety in the way shown.
SCJP2. Please Indent your code using UBB Code
Joined: Jul 03, 2001
ObjectWrapper1 is not thread safe because even though the accessor method returns a copy of the instance of Content, two objectWrapper1 could be constructed pointing to the same Content object. In that case they are sharing the same content. Two threads with a reference to the objectWrapper1s could mess each other by changing the object returned by the accesor methods. ObjectWrapper2 is thread safe because avoid the previous problem via making a copy of the argument to its constructor.