• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

locking objects that only read fields

 
Bod Toki
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Please any thoughts on locking objects in which only the constructors can write (or set) fields. These objects do not share any static (Class) fields.

In my opinion i think locking would be unneccessary here- allowing multiple threads reading an objects field would not corrupt data.
 
Mark Smyth
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you are sayin should be fine but it does depend on what exactly your constructor does. Just because there are no static variables in a class does not mean that one instance cannot affect another.
Consider the following (extremely contrived) arrangement.



There are no static variables in the class. However as arrays(and all objects) are passed by reference in java, a and b share the same numbers array. So changes to the numbers in a will affect b and vice versa.

[ October 27, 2006: Message edited by: Mark Smyth ]
[ October 27, 2006: Message edited by: Mark Smyth ]
 
Bod Toki
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I meant a class without setter methods. All variable settings are done in the constructor when the object is created and remain so throuthout the existence of the objects. The only public methods available from the objects are getter methods....

as in this example:



What do you think about this kind of situation. Or is there still a chance that multithreading could corrupt this object's data?
 
Mark Smyth
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well if there are only primitive types in the object it should be fine
Mark
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic