• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static methods and synchronization  RSS feed

 
Sam Drake
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a doubt on static methods and attributes of an object.
Are static method and properties inherently handling multi-threading? That is, when multiple threads simultaneously try to change value for a static property will they be synchronized themselves or do we need to add code for that.
Say I have an attribute at class level -
pirvate static BigDecimal ob = new BigDecimal();
public static void changeValue(BigDecimal obj2) {
ob.add(obj2);
.........
.........using ob to do some other changes
}
Qn is when 2 threads simulatenously call changeValue will they be synchronized if the method is declared static.
Thanks,
Sam.
 
Eddie Vanda
Ranch Hand
Posts: 283
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sam,
The static keyword simply means that the method is not instantiated when the class is, ie, you need to mention the class name with the method. You only need to worry about being thread safe when you are running more than one thread. In that case you still need to synchronize the method.
Ed
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Qn is when 2 threads simulatenously call changeValue will they be synchronized if the method is declared static.

In your given example, no, that method is not thread-safe.
Perhaps you are misunderstanding the purpose of the static keyword.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!