• 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:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Static methods and synchronization

 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 283
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Let's get him boys! We'll make him read this tiny ad!
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic