Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

thread safe method calls

 
Pete Kleczka
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello

If I have a class that is accessed by multiple threads (e.g. Spring bean with singleton scope used in a web application) can I chain methods safely without synchronizing. That is, if I have method: public String getStuff(), and that method calls on several private helper methods on the same class, do I have to synchronize on the private helpers? These helper methods will simply return values to the getStuff() method, they will not access any class level variables.

Thanks in advance for your answers.
Peter
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pete Kleczka wrote:
If I have a class that is accessed by multiple threads (e.g. Spring bean with singleton scope used in a web application) can I chain methods safely without synchronizing. That is, if I have method: public String getStuff(), and that method calls on several private helper methods on the same class, do I have to synchronize on the private helpers?


If all the calls to those private methods comes from code that's already synced, then no, you don't have to. Once you obtain the lock, you keep it until you leave the sync block or call wait().

If, however, you also call those private methods from an unsynced method or block, then, yes, you have to sync those private methods.

 
Andi Eska
Greenhorn
Posts: 14
BSD Eclipse IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If, however, you also call those private methods from an unsynced method or block, then, yes, you have to sync those private methods.


As long as those private method don't access any fields i.e. class level variables it's not necessary to sync those private methods.


If I have a class that is accessed by multiple threads (e.g. Spring bean with singleton scope used in a web application) can I chain methods safely without synchronizing.

The other question wouldn't it be better to use a request scope bean so that there is no need to synchronize the method(s).

andi
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Andi Eska wrote:
If, however, you also call those private methods from an unsynced method or block, then, yes, you have to sync those private methods.


As long as those private method don't access any fields i.e. class level variables it's not necessary to sync those private methods.


Oops. Didn't notice that part of the OP.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic