• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

some question about static methods and Thread safety , please

 
Ranch Hand
Posts: 551
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
Thank you for reading my post.
1-Are static methods thread safe ? I mean if i declare a method to be static , will it run in guarded mode ?
2-if static methods are thread safe , does JVM run them internally in Synchronized mode?

by static method i mean :

Thank you
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Static-ness and thread safety are unrelated concepts. The JVM runs them in synchronized mode only if they're declared to be synchronized, or part of a synchronized block. So a static method needs to take the same precautions a non-static method would take against concurrent access problems.
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In general what makes something unsafe is two threads locking or modifying a shared resource like an object, file, database or partner system. Your method didn't do that, so it's ok for now.

You could have a shared resource as a static varible, a parameter, a member variable on a singleton, anything you get from another method, anything you give to another method or something external to your code. I bet there are more ways I didn't think of just now. All this can make maintaining thread safety kind of tricky!
 
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
raminaa,

Are you aware that static methods can be modified by the keyword "synchronized", and that the following two ways of making a static method synchronized are equivalent?
 
reply
    Bookmark Topic Watch Topic
  • New Topic