Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

static member's synchronization

 
Rauhl Roy
Ranch Hand
Posts: 401
Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,,

can we synchronization static methods blocks..etc? if not.. why we can not do on it. is it just because we static variables and methods are do not belong to class?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static methods and variables belong to the class, not any particular instance of the class. So a synchronized static method synchronizes on the class itself. A thread must get the monitor on the class before entering the method.

A block synchronized on a static variable gives roughly the same effect; a thread must get the monitor for the object referenced by that variable before entering the block. No matter how many instances there are, they are all synchronized on the same object.

Does that make sense?
 
Ken Blair
Ranch Hand
Posts: 1078
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Stan James:

A block synchronized on a static variable gives roughly the same effect; a thread must get the monitor for the object referenced by that variable before entering the block. No matter how many instances there are, they are all synchronized on the same object.


With the unstated assumption that the value of the variable hasn't been changed to point at a different object.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!