• 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:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Synchronizing a static method

 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).]
 
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic