• Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronizing a static method

 
Sri Bala
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found static method being synchronized in another post and I tried it. On what object is the synchronization done?

[This message has been edited by Sri Bala (edited November 25, 2001).]
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A synchronised static method synchronises on the class's Class object. There is exactly one of these, so it means that only one synchronised static method can be operating on that Class at any one time.
The Class object is for exactly that class, not its subclasses. Therefore, synchronised static methods on a subclass can run simultaneously with synchronised static methods on the base class.
I am told that internal operations also sometimes synchronise on the Class object. Therefore, static synchronised methods may be blocked more often than you think.
For these and other reasons, synchronised static methods are often a bad idea. Instead, you can declare a static "lock" object and synchronise explicitly on that. This method is particularly good if you want to involve subclasses in the synchronisation. If the lock object is given protected access, subclasses can synchronise on it, too.
The "lock" object can be of class java.lang.Object, because you don't actually want to use it for anything else and Object is the smallest thing you can create.
You can have more than one "lock" object, if you want to define more-complex class-level synchronisation semantics.
 
Sri Bala
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Peter. I was surprised about the possibility of synchronizing static methods. Though it is not advisable to synchronize on the Class object, it's good to know that it's possible.
Cheers,
Sri.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!