Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Will this class be always safe to use in a multi-threaded environment?

 
Gesu Saguzo
Greenhorn
Posts: 12
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Mala Gupta's book it is said that this class is thread-safe:


Is that true in all the cases? What's if we use the read() method to obtain the value parameter and we modify its attributes?

Thanks.
 
Stephan van Hulst
Bartender
Posts: 6587
86
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Difficult to say without knowing the purpose and responsibilities of ESafe. It doesn't seem to be doing anything with value, so I would argue that it would be thread-safe by virtue of value being final, even without the use of the synchronized keyword.

Being able to modify the attributes of value outside of an instance of ESafe has nothing to do with being thread-safe.
 
Gesu Saguzo
Greenhorn
Posts: 12
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Stephan for your answer.


I also thought that being able to modify the attributes of value has nothing to do with being thread-safe. However in this book it is written: Immutable objects like an instance of class String and all the wrapper classes are thread safe because their contents can't be modified.

On the other hand, this example of thread-safe class made me think that ESafe might not be thread-safe (look at the (Date)birth.clone() part):
 
Stephan van Hulst
Bartender
Posts: 6587
86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, immutable objects are thread-safe by definition.

If two different threads called read() on the same ESafe instance, and they would both make edits to the returned value, it's possible that one thread doesn't see the updates that the other thread made. That doesn't mean ESafe isn't thread-safe, that means the object it returns isn't thread-safe.

Honestly, this is a very confusing example in my opinion. You should never ever write code like the ESafe class. Maybe it's best forgotten.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!