File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronizing

 
Raju Champaklal
Ranch Hand
Posts: 521
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in k&b it is mentioned that
If you have
methods that don't access the data you're trying to protect, then you don't
need to synchronize them


data you're trying to protect

does this refer to variables that are private?

what if the data is public.... should we still need to synchronize them?
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Raju,

in general all SHARED and MUTABLE data have to be synchronized if it could be a problem in your application when more than one thread has access to it! It doesn't matter if the data (= variables) are public themselves or you directly expose them via public methods.

But as easy as this may sound it's usually up to the programmer to decide which data could be accessed concurrently and if this could lead to problems. If some data are guaranteed not to be shared among several threads or perhaps it's simply not that critical if the shared data are consistent all the time you may decide to ignore concurrency effects. Of course in most cases you wouldn't want to risk inconsistent data though.

Marco
 
Raju Champaklal
Ranch Hand
Posts: 521
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh yes...understood...i thought protect the data means only private data...but even public data that can be shared can be protected so that it doesnt give odd results
Thanks
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's in particular publicly accessible data which you have to protect! Private data can only be shared between objects of the class they belong to, so they don't have very much potential to cause concurrency bugs.

There are a lot more details to this. For example even with a synchronized getter method you ca indirectly (and accidentally) share data if you simply return a Date or a (mutable) List. This way other objects could from the outside modify the returned List without your object knowing about it. Then you have created mutable shared data even though the evil getter method which returned the collection was synchronized

Marco
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic