• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Is synchronisation only relevant when two (or more) methods can access a variable ?

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi guys, wondering if anyone could give me some guidance on this.

In a multithreaded application, if methodA() and methodB() can both change the value of a variable X, I can add the synchronized keyword to both methods. Then, when a thread calls synchronized methodA() and acquires the monitor, this prevents another thread from calling synchronized methodB() until the first thread gives up the monitor. The result is that only one of the synchronized methods can access variable X at any given time.

But say only methodA() can access variable X. In what circumstances would I want to ensure that two threads did not attempt to call methodA() ? Intuitively it feels right that I would want to avoid that but would be interested in

- hearing of any particular examples of when I really should synchronize a single method ?
- does this means that in a multi-threaded application I should synchronize all data access (using synchronized methods/statements) ?

Thanks, John
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Synchronization is required only for cases where you can have simultaneous access to shared, mutable state. If one of those conditions does not apply then you don't need to synchronize.

If the only state you are accessing in a method is immutable, then synchronization is not necessary.

It is possible that a single method needs to be synchronized if it accesses a value that is mutable and is in a scope where changes can be simultaneously observed from multiple threads. The scope of a variable is an important consideration. For example, a class field can be accessed by multiple instances of the same class. Even if you only have one object and one method, if you have multiple threads using that same object and accessing the same mutable class-level variable via one method, you'd still need to synchronize.

Note that variables local to a method are always thread safe. Primitive parameters are thread safe. Parameters that are object references need some study to determine if they are thread safe though but usually they are. Again, it goes back to the scope of the object being referenced by that parameter.

Show us some code so we can get more specific. There are too many nuances to cover in one response.
 
John Mulholland
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Very clear and informative Junilu. I appreciate your comments.
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

John Mulholland wrote:In a multithreaded application, if methodA() and methodB() can both change the value of a variable X, I can add the synchronized keyword to both methods. Then, when a thread calls synchronized methodA() and acquires the monitor, this prevents another thread from calling synchronized methodB() until the first thread gives up the monitor. The result is that only one of the synchronized methods can access variable X at any given time.


Basically, that's correct but, as Junilu pointed out, variable X will usually be part of a class whose state needs to be synchronized.

But say only methodA() can access variable X. In what circumstances would I want to ensure that two threads did not attempt to call methodA() ? Intuitively it feels right that I would want to avoid that but would be interested in
- hearing of any particular examples of when I really should synchronize a single method ?
- does this means that in a multi-threaded application I should synchronize all data access (using synchronized methods/statements)?


Phew. That's a fairly big question because (unfortunately) synchronization applies to both writing and reading; so a seemingly innocuous thing like ++i, which involves both a read AND a write, can be "interfered with" by unsynchronized attempts to do the same thing, or even just to read the "current state" of i.

In the absence of synchronization, the Java compiler is allowed to perform all sorts of optimizations that make code run quicker, like storing values locally and re-ordering instructions (provided they have the same logical outcome) so, yes, your "intuition" is right: synchronization slows things down, and also makes testing more complex, so if you can avoid it, it's generally preferable. And even if it's required (as it sometimes is), you generally want to keep synchronized blocks or methods as short as possible - especially in terms of execution time.

However, without going into all the 'in's and 'out's of the Java memory model, or the intricacies of "happens-before" logic, it's very difficult to give generalizations on HOW you should do it.
My suggestion would be to start with the tutorials, and come back if you have a specific question on something you don't follow in there.

I should add that the synchronized keyword is no longer the sole form of synchronization; and others (eg, ReentrantLocks) are arguably better; but it's by no means cut-and-dried.

HIH

Winston
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic