Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

is synchronized needed here?  RSS feed

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
EX1
HERE, i think BOTH Methods must be synchronized.
Because one thread of control might be getting, and at the same time another thread of control setting x, the getter might return an inconsistent value.

another
BUT Here, I think only the setter method should be synchronized, while our private var is a final Object, the reference variable will be all the time referring to the same instance object, even though the fields' values within this object might be changed. So even though Thread of Control passes from a thread using getter, to another thread using setter method, the code is safe. Am I right?
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by R�stem e Zal:
EX1 [...] HERE, i think BOTH Methods must be synchronized.
Yes; alternatively, you could declare the field x "volatile". Characters are read and written atomically.
another [...]BUT Here, I think only the setter method should be synchronized [...] Am I right?
No. The second code snippet is a good example of a class that cannot be made threadsafe simply by synchronizing the class methods. When the setter is called, the values for i and j in the WWW object are changed. This should really be atomic with respect to all other threads accessing this object. Your problem now is that other threads may have references to WWW (obtained through getX) and you have no control over how and when these references are used. You could solve this by encapsulating the fields i and j using getters, and synchronizing those. The setX method might then look as follows:This still doesn't solve the issue that threads, having obtained a WWW using getX(), might find that its values change from one moment to the next. Usually not good. In order to prevent this, code using a WWW will probably want to synchronize on the WWW object to prevent modification for the duration. This obviously reduces concurrency; your first snippet was much better behaved in that respect.

Note that similar problems can arise when you retrieve an Iterator from a synchronized Collection - in order to be threadsafe, you must retrieve the Iterator and perform the iteration in a block that is synchronized on the Collection. See the javadoc for Collections.synchronizedCollection().

Why the built-in synchronization in Vector, Hashtable and friends is usually worse than useless is left as an exercise for the reader.

- Peter
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!