• Post Reply Bookmark Topic Watch Topic
  • New Topic

What's the best way to synchronize?  RSS feed

 
Ryan P. Kane
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I have a question about synchronization. I have a method that must be run synchronously, not just for the instance, but for all of my instances of this class that are in my pool. If I have a pool of java objects of class MyClass, and if I make tje non-static method on MyClass synchronized, calls to that method will only be synchronized on one instance from the pool, right? If it were a static method, I believe it would synchronize for all instances in the pool, but I don't want the method to be static. So to synchronize a method call when I have a pool of objects, is better to put a synchronize block in the method?

Thanks,
Ryan
 
Bill Johnston
Ranch Hand
Posts: 201
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan P. Kane wrote:Hello,

I have a question about synchronization. I have a method that must be run synchronously, not just for the instance, but for all of my instances of this class that are in my pool. If I have a pool of java objects of class MyClass, and if I make tje non-static method on MyClass synchronized, calls to that method will only be synchronized on one instance from the pool, right? If it were a static method, I believe it would synchronize for all instances in the pool, but I don't want the method to be static. So to synchronize a method call when I have a pool of objects, is better to put a synchronize block in the method?

Thanks,
Ryan


You need to add the synchronized keyword to the code you want synchronized, yes. I'm not sure I understand beyond that what you are asking. Is you question about synchronizing a block of code vs the entire method?
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan P. Kane wrote:So to synchronize a method call when I have a pool of objects, is better to put a synchronize block in the method?

Sounds good to me. How about
synchronized (myPool) { ...
?

[Edit] An alternative might be to add a synchronized method to the Pool class itself.

Winston
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!