This week's book giveaway is in the Agile forum.
We're giving away four copies of Head First Agile and have Andrew Stellman & Jennifer Greene on-line!
See this thread for details.
Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Does a getter( ) to shared data that doesn't change need to be synchronized?  RSS feed

 
Bill Smyth
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Imagine I have this class:



and that objects running in multiple threads call the method getObject(int i). In this case, is it necessary to declare getObject(int i) syncchronized? I wouldn't think so because the objs array is initialized in a static block and never changed. But I'd like a sanity check

Thanks in advance!
 
Henry Wong
author
Sheriff
Posts: 23284
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bill Smyth wrote:
and that objects running in multiple threads call the method getObject(int i). In this case, is it necessary to declare getObject(int i) syncchronized? I wouldn't think so because the objs array is initialized in a static block and never changed. But I'd like a sanity check


Agreed. There is no need to synchronize the access of data that does not change.

Henry
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are going to use getters without synchronized it would be good form to add a thread safety comment or add an annotation for other developers, as it may not be obvious on first reading you have considered this. If in doubt synchronize as in theory the JVM should just optimise the cost away in this example to nothing and gotchas in this area can be quite complex.

Your code is thread safe because its immutable and correctly published on construction ie used static initialisation with has special properties in the Java Memory Model. You might also want to consider using final though it isn't necessary in this example it gives a good idea of intent.

 
Rahul Mahindrakar
Ranch Hand
Posts: 1869
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Agree with chris here. It seems that you will need to code in a way that shows your intent. If a new programmer comes along then he could put in code that might break your intent.

But would making the object final make the array contents not changeable. Hmm i need to think how to do this.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!