Win a copy of Learning Regular Expressions this week in the General Computing forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

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

 
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.
 
Saloon Keeper
Posts: 9257
177
  • 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
Saloon Keeper
Posts: 9257
177
  • 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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!