• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static synchronized methods  RSS feed

 
Sam Samson
Ranch Hand
Posts: 63
IntelliJ IDE Java jQuery
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Can a static synchronized method be accessed alternately when it is invoked from two different objects?

Isn't there only one lock for a static synchronized method and once it gets called it acquires the lock so no other object (even though it's a different one) can't execute this method?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A static synchronized method is synchronized on the class object. So you're right, only one object can call it at a time.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sam Samson wrote:Hi

Can a static synchronized method be accessed alternately when it is invoked from two different objects?


We don't invoke methods "from objects." We invoke them from threads, and it's the threads that exclude each other, not the objects.

There's nothing special about a static synced method. Just like every single use of synchronization, all it does in terms of mutual exclusion is that it obtains an object's lock, first waiting until it's released if some other thread currently holds it. That's it. Nothing else.

Isn't there only one lock for a static synchronized method


No. There's one lock per object. Period.



All the syncings do the same thing: Obtain one object's lock. Declaring a method synchronized is just shorthand for syncing the entire method body on a specific lock. The only difference between a static synced method and a non-static one is which object's lock we're obtaining.







 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:A static synchronized method is synchronized on the class object. So you're right, only one object can call it at a time.


Only one thread can, just like when we obtain some other object's lock.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!